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

023*_*5ev 6 python plot matplotlib

我正在尝试使用 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')
Run Code Online (Sandbox Code Playgroud)

结果如下图: 数字

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

谢谢您的帮助。

Pri*_*mer 6

You could replace your legend setting lines with these:

ax1.legend(loc=1, borderaxespad=1.).set_zorder(2)
ax2.legend(loc=2, borderaxespad=1.).set_zorder(2)
Run Code Online (Sandbox Code Playgroud)

And it should do the trick.

Note that locations have changed to correspond to the lines and there is .set_zorder() method applied after the legend is defined.

The higher integer in zorder the 'higher' layer it will be painted on.在此处输入图片说明


Bky*_*kyn 6

诀窍是绘制您的第一个图例,将其删除,然后使用 add_artist() 在第二个轴上重新绘制它:

legend_1 = ax1.legend(loc=2, borderaxespad=1.)
legend_1.remove()
ax2.legend(loc=1, borderaxespad=1.)
ax2.add_artist(legend_1)
Run Code Online (Sandbox Code Playgroud)

向@ImportanceOfBeingErnest 致敬:https :
//github.com/matplotlib/matplotlib/issues/3706#issuecomment-378407795