如何在 matplotlib 中将图例的右上角锚定到轴的右上角?

qsf*_*fzy 0 python matplotlib legend

我试图将 matplotlib 图的图例恰好定位在轴的右上角,以便图例的边缘和轴的边缘之间没有微小的线条部分。我想通过直接调用 Legend 对象的方法来完成此操作,例如Legend.set_bbox_to_anchor(),但我的尝试似乎根本没有移动图例。

这是我最近的尝试:

leg.set_bbox_to_anchor((1,1), transform = ax.transAxes)
Run Code Online (Sandbox Code Playgroud)

其中leg是 Legend 对象,ax是父 Axes 对象。您对我如何实现这一目标有什么想法吗?

Ton*_*ino 5

尝试plt.legend(bbox_to_anchor=(1, 1), loc=1, borderaxespad=0)