首页 > 解决方案 > Python:从 x 轴上的点 (X1,0) 到点 (X2,Y2) 的绘图问题

问题描述

我在 X 轴上有点,我想从每个点到另一个点(X2,Y2)做直线。

此代码适用于从 Y=35 到 X 点 ( P) 的蓝线,它可以工作

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()

这里是应该做我在开头描述的代码:


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()

我的期望在附图上(我有红色和紫色的点,我不知道如何做绿线)。

这段代码(第二个)显示了几十个图表(每条绿线分别),不包括(我希望)之前的代码/之前的图表。

图片

标签: pythonpython-3.xnumpymatplotlibplot

解决方案


您正在每个循环上创建一个图形。您可以先设置您的图形,然后在for循环中添加线条。像这样重新排列您的代码:

# 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()

推荐阅读