macaroni
macaroni

Reputation: 151

Python: Problem with plotting lines from points (X1,0) on x axis to points (X2,Y2)

I have points on X axis and i want to do straight line from each of them to another point (X2,Y2).

This code is for blue lines from Y=35 to X points (P) and it work

pos_fixed = np.array([0, TR])
lines = np.array([[[pos, 0], pos_fixed] for pos in P])
line_coll = LineCollection(lines)

fig, ax = plt.subplots()
ax.add_collection(line_coll)

plt.xlim([0, lines[:,:,0].max()])
plt.ylim([0, lines[:,:,1].max()])
plt.xlabel('Oś')
plt.ylabel('Promień')
plt.show()

And here is code which should do what i describe at the beginning:


for s in range(len(P)-1):
    position = np.array([P[s], 0])
    lines = np.array([[position, [x2[s], y2[s]]]])
    line_coll = LineCollection(lines)
    fig, ax = plt.subplots()
    ax.add_collection(line_coll)
    plt.xlim([0, lines[:,:,0].max()])
    plt.ylim([0, lines[:,:,1].max()])
plt.show()

My expectations are on attached picture (i have red and purple points and i dont know how to do green lines).

This code (the second one) displays dozens of charts (each green line separately) and does not include (I wish to) the previous code/previous chart.

Picture

Upvotes: 1

Views: 51

Answers (1)

Ali Kazemkhanloo
Ali Kazemkhanloo

Reputation: 1159

you are creating a figure on each loop. You can first set up your figure and then in the for loop add the lines. rearrange your code like this:

# create the figure
fig, ax = plt.subplots()
plt.xlim([0, lines[:,:,0].max()])
plt.ylim([0, lines[:,:,1].max()])

# lines from the first part of the question
pos_fixed = np.array([0, TR])
lines = np.array([[[pos, 0], pos_fixed] for pos in P])
line_coll = LineCollection(lines,colors='blue')
ax.add_collection(line_coll)
plt.xlabel('Oś')
plt.ylabel('Promień')


# lines for the second part
for s in range(len(P)-1):
    position = np.array([P[s], 0])
    lines = np.array([[position, [x2[s], y2[s]]]])
    line_coll = LineCollection(lines,colors='green')
    ax.add_collection(line_coll)

plt.show()

Upvotes: 1

Related Questions