我正在尝试使用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')结果如下图所示:

如图所示,在ax1图例上绘制来自ax2的数据,我希望图例在数据的顶部。这里我漏掉了什么?
谢谢你的帮助。
发布于 2019-02-11 21:09:49
诀窍是绘制第一个图例,删除它,然后使用add_artist()在第二个轴上重新绘制它:
legend_1 = ax1.legend(loc=2, borderaxespad=1.)
legend_1.remove()
ax2.legend(loc=1, borderaxespad=1.)
ax2.add_artist(legend_1)致敬@ImportanceOfBeingErnest:
https://github.com/matplotlib/matplotlib/issues/3706#issuecomment-378407795
发布于 2015-03-12 22:13:12
您可以使用以下内容替换图例设置行:
ax1.legend(loc=1, borderaxespad=1.).set_zorder(2)
ax2.legend(loc=2, borderaxespad=1.).set_zorder(2)它应该能起到这个作用。
请注意,位置已更改为与线相对应,并且在定义图例后应用了.set_zorder()方法。
zorder中的整数越高,它将被绘制在“更高”的图层上。

https://stackoverflow.com/questions/29010078
复制相似问题