I know there is another very similar question, but I could not extract the information I need from it.
I have 4 points in the
x=[-1 ,0.5 ,1,-0.5] y=[ 0.5, 1, -0.5, -1]
Now, I can plot the four points by doing:
import matplotlib.pyplot as plt plt.plot(x,y, 'ro') plt.axis('equal') plt.show()
But, apart from the four points, I would like to have 2 lines:
1) one connecting
2) the second one connecting
This is a simple toy example. In the real case I have 2N points in the plane.
How can I get the desired output: for points with two connecting lines ?
This question is tagged with
~ Asked on 2016-02-12 13:08:51
I think you're going to need separate lines for each segment:
import numpy as np import matplotlib.pyplot as plt x, y = np.random.random(size=(2,10)) for i in range(0, len(x), 2): plt.plot(x[i:i+2], y[i:i+2], 'ro-') plt.show()
numpy import is just to set up some random 2x10 sample data)
~ Answered on 2016-02-12 13:23:37
You can just pass a list of the two points you want to connect to
plt.plot. To make this easily expandable to as many points as you want, you could define a function like so.
import matplotlib.pyplot as plt x=[-1 ,0.5 ,1,-0.5] y=[ 0.5, 1, -0.5, -1] plt.plot(x,y, 'ro') def connectpoints(x,y,p1,p2): x1, x2 = x[p1], x[p2] y1, y2 = y[p1], y[p2] plt.plot([x1,x2],[y1,y2],'k-') connectpoints(x,y,0,1) connectpoints(x,y,2,3) plt.axis('equal') plt.show()
Note, that function is a general function that can connect any two points in your list together.
To expand this to 2N points, assuming you always connect point
i to point
i+1, we can just put it in a for loop:
import numpy as np for i in np.arange(0,len(x),2): connectpoints(x,y,i,i+1)
In that case of always connecting point
i to point
i+1, you could simply do:
for i in np.arange(0,len(x),2): plt.plot(x[i:i+2],y[i:i+2],'k-')
~ Answered on 2016-02-12 13:21:55