我正在尝试使用 Python 和 Matplotlib 来绘制许多不同的数据集。我正在使用 twinx 将一个数据集绘制在主轴上,另一个绘制在次轴上。我想为这些数据集提供两个单独的图例。

在我当前的解决方案中,来自辅助轴的数据绘制在主轴图例的顶部,而来自主轴的数据未绘制在辅助轴图例上。

我根据此处的示例生成了一个简化版本:http://matplotlib.org/users/legend_guide.html

这是我到目前为止所拥有的:

import matplotlib.pyplot as plt
import pylab

fig, ax1 = plt.subplots()
fig.set_size_inches(18/1.5, 10/1.5)
ax2 = ax1.twinx()

ax1.plot([1,2,3], label="Line 1", linestyle='--')
ax2.plot([3,2,1], label="Line 2", linewidth=4)

ax1.legend(loc=2, borderaxespad=1.)
ax2.legend(loc=1, borderaxespad=1.)

pylab.savefig('test.png',bbox_inches='tight', dpi=300, facecolor='w', edgecolor='k')

结果如下图:

如图所示,来自 ax2 的数据被绘制在 ax1 图例上,我希望图例位于数据的顶部。我在这里缺少什么?

谢谢您的帮助。

最佳答案

你可以用这些替换你的图例设置行:

ax1.legend(loc=1, borderaxespad=1.).set_zorder(2)
ax2.legend(loc=2, borderaxespad=1.).set_zorder(2)

它应该可以解决问题。

请注意,位置已更改为对应于线条,并且在定义图例后应用了 .set_zorder() 方法。
zorder 中较高的整数表示将在其上绘制的“较高”层。

关于python - Matplotlib:使用 twinx 时在图例上绘制数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29010078/

10-12 16:43
查看更多