Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib continuing line into infinity

I have a graph, made from data in .txt files. Currently, Matplotlib will graph it to the last point in my file. I need it to continue farther that that. I seem to remember something somewhere saying that I could make a line continue into infinity. (I don't mean infinity when using calculus and limits, I just mean a line going of the screen, until the edge of the graph.)

Now, I know this would not be accurate if I had a curved graph, because the line would continue forever at the angle out of the last datapoint. However, since I have a straight-line graph, this would be ideal.

Does anyone know if this is possible and if so, how? I have done research, and cannot remember where I saw the doc entry saying I could do this, so if someone could shed light on this I'd really appreciate it.

like image 430
CoilKid Avatar asked Sep 04 '14 22:09

CoilKid


2 Answers

On a scale from one to hacky, this is pretty hacky, but you can ask matplotlib what the current bounds of the plot are

import matplotlib.pyplot as plt

plt.plot([0,10], [0,10])
plt.axis()

returns:

(0.0, 10.0, 0.0, 10.0)

This is super clunky, but you could figure out the equation of the line of the last two points, and then figure out where that line intersects the bounding box. Then plot a line from the last point to the BB.


New idea, slightly less clunky. Extend the line of the last two points, then set the axes back to what they were.

import numpy
import matplotlib.pyplot as plt

X = [0, 1, 2]
Y = [4, 6, 4]

plt.plot(X,Y)
axes = plt.axis()
plt.plot([X[-2],X[-2]+1000*(X[-1]-X[-2])], [Y[-2],Y[-2]+1000*(Y[-1]-Y[-2])])
plt.xlim( [axes[0], axes[1]])
plt.ylim( [axes[2], axes[3]])
plt.show()
like image 132
Mike Ounsworth Avatar answered Oct 17 '22 17:10

Mike Ounsworth


As of v3.3 a new axline method has been added to draw infinitely long lines that pass through two points:

import matplotlib.pyplot as plt 

fig, ax = plt.subplots()

ax.axline((.1, .1), slope=5, color='C0', label='by slope')
ax.axline((.1, .2), (.8, .7), color='C3', label='by points')

ax.legend()

enter image description here

like image 4
iacob Avatar answered Oct 17 '22 18:10

iacob