显示图例
注意:如果只在plt.plot()中设置label还不能最终显示出图例,还需要通过plt.legend()将图例显示出来。
# 绘制折线图
plt.plot(x, y_shanghai, label="上海")
# 使用多次plot可以画多个折线
plt.plot(x, y_beijing, color='r', linestyle='--', label="北京")
# 显示图例
plt.legend(loc="best")

显示图例的位置loc=""
| Location String | Location Code |
|---|---|
| 'best' | 0 |
| 'upper right' | 1 |
| 'upper left' | 2 |
| 'lower left' | 3 |
| 'lower right' | 4 |
| 'right' | 5 |
| 'center left' | 6 |
| 'center right' | 7 |
| 'lower center' | 8 |
| 'upper center' | 9 |
| 'center' | 10 |
这篇博客介绍了如何在Python的matplotlib库中绘制折线图,并重点讲解了如何通过`plt.legend()`函数来正确显示图例,包括图例的位置控制如`loc=best`等。示例代码展示了如何为不同线条设置标签并最终展示图例,帮助读者理解在图表中添加图例的重要性。
1725

被折叠的 条评论
为什么被折叠?



