我来到这里,因为我有同样的问题,但想要两个独立的传说,每一个双轴一个。
@ImportanceOfBeingErnest提供的公认答案不再有效,因为它只允许将一个图例附加到
ax2
https://github.com/matplotlib/matplotlib/issues/3706#issuecomment-378407795
.
我将它们都转换为一个函数,我通常在本例中使用这个函数,并认为在这里提供它会很有用:
def legend_to_ax( ax, ax_placein=None, method=2, **kwargs ):
""" Wrapper around ax.legend(**kwargs) which permits to have the legend
placed in the axis ax_placein.
This is useful when drawing legends for multiple axes, e.g.produced with
ax2 = ax1.twinx(), in order to have all legends on top of all axes.
In this case provide the uppermost axis, e.g. ax2 here, as ax_placein.
Args:
- ax : axis for which the legend is created
- ax_placein : axis which the legend should be placed in (optional)
- method : method by which to handle the placement of the legend in
ax_placein.
method=1 ... based on
https://stackoverflow.com/a/45336414/7042795
This method fails when multiple legends should
be added to ax_placein.
method=2 ... based on
https://github.com/matplotlib/matplotlib/issues/3706#issuecomment-378407795
This adds the legend as an artist to ax_placein
making it no longer appear via ax.get_legend().
Instead parse ax_placein.artists()
- **kwargs : kwargs of ax.legend()
Returns:
- leg : legend handle
"""
if ax_placein is None:
leg = ax.legend(**kwargs)
elif method==1:
# based on https://stackoverflow.com/a/45336414/7042795
h, l = ax.get_legend_handles_labels()
if ax_placein is not None:
ax = ax_placein
leg = ax.legend( h, l, **kwargs)
elif method==2:
# based on https://github.com/matplotlib/matplotlib/issues/3706#issuecomment-378407795
leg = ax.legend(**kwargs)
if ax_placein is not None:
leg.remove()
ax_placein.add_artist(leg)
return leg
因此,使用此函数,您可以简单地执行以下操作
legend = legend_to_ax( ax, ax_placein=ax2, method=1, facecolor="white")
或
legend = legend_to_ax( ax, ax_placein=ax2, method=2, facecolor="white")
legend1 = legend_to_ax( ax, ax_placein=ax2, method=2, facecolor="white", loc="upper left")
legend2 = legend_to_ax( ax2, ax_placein=ax2, method=2, facecolor="white", loc="upper right")