python - 主 Y 轴的绘图标签不显示

标签 python matplotlib

我从 Stackoverflow 复制了一些代码来使用辅助 Y 轴,以提高图表的可读性。遗憾的是,仅显示一个 y 轴的图例。

显示的内容是我使用 plt.legend() 包含的内容。但是,如果我尝试同时显示两者,请使用

ax1.legend()

ax2.legend()

仅显示后者。这是完整的代码

import matplotlib.pyplot as plt

x,y1,y2,y3,y4=[1,2],[0.5,1],[1,4],[1,2],[1,1.5]

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()

ax1.plot(x, y1, 'g-', label='y1')
ax1.plot(x, y2, 'r-', label='y2')
ax2.plot(x, y3, 'b-', label='y3')
ax2.plot(x, y4, 'y-', label='y4')

ax1.legend()

ax2.legend()

plt.show()

enter image description here 怎么才能全部显示在图例中呢?

最佳答案

您可以尝试使用:

plt.legend(loc='左上')

而不是:

ax1.legend()

ax2.legend()

可能在您的原始数据中,您的标签重叠,并且仅显示最后一个 (ax2)。

关于python - 主 Y 轴的绘图标签不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57405838/

相关文章:

python - 使用 scrapyd 运行多个爬虫

python - 二维数组意外赋值错误

python - 性能比较 静态类型 Python 3.6+ 与 Cython

python - 我可以通过另一个变量中的值为 seaborn distplot 着色吗?

python - matplotlib 接受不同颜色形式的问题

python - 绘制表示边权重的连续宽度图例

python - 平方 (x^2) 近似的神经网络

Python在检测数组的排名后如何删除垃圾列

python - 如何将动态pyplot保存为电影文件?

python - 在 matplotlib 中叠加 pcolormeshes