Matplotlib:使用twinx时,数据在图例上绘制

时间:2015-03-12 12:43:32

标签: python matplotlib plot

我正在尝试使用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')

结果如下: Figure

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

您可以使用以下内容替换图例设置行:

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

它应该可以解决问题。

请注意,位置已更改为与行对应,并且在定义图例后应用了.set_zorder()方法。

zorder“更高”图层中的较高整数。enter image description here

答案 1 :(得分:1)

诀窍是绘制第一个图例,将其删除,然后使用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