Python中一个图中的多个图

新手上路,请多包涵

我是 python 的新手,正在尝试使用 matplotlib 在同一个图中绘制多条线。我的 Y 轴的值存储在字典中,我在下面的代码中在 X 轴中创建相应的值

我的代码是这样的:

 for i in range(len(ID)):
AxisY= PlotPoints[ID[i]]
if len(AxisY)> 5:
    AxisX= [len(AxisY)]
    for i in range(1,len(AxisY)):
        AxisX.append(AxisX[i-1]-1)
    plt.plot(AxisX,AxisY)
    plt.xlabel('Lead Time (in days)')
    plt.ylabel('Proportation of Events Scheduled')
    ax = plt.gca()
    ax.invert_xaxis()
    ax.yaxis.tick_right()
    ax.yaxis.set_label_position("right")
    plt.show()

但是我一个一个地得到单独的数字和一个情节。谁能帮我弄清楚我的代码有什么问题?为什么我不能生成多线绘图?非常感谢!

原文由 user3183660 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 276
2 个回答

这很简单:

 import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.legend(loc='best')
plt.show()

您可以继续添加 plt.plot 多次。至于 line type ,需要先指定颜色。所以对于蓝色,它是 b 。对于普通线路,它是 - 。一个例子是:

 plt.plot(total_lengths, sort_times_heap, 'b-', label="Heap")

原文由 Games Brainiac 发布,翻译遵循 CC BY-SA 3.0 许可协议

由于我没有足够高的声誉来发表评论,我将在 2 月 20 日 10:01 回答 liang 问题作为对原始问题的回答。

为了显示行标签,您需要将 plt.legend 添加到您的代码中。以上面的示例为基础,该示例还包括标题、ylabel 和 xlabel:

 import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.title('title')
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.legend()
plt.show()

原文由 Stian 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题