我正在尝试使用 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 图例上,我希望图例位于数据顶部。我在这里缺少什么?
谢谢您的帮助。