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

问题描述 投票:0回答:2
我试图将 matplotlib 图的图例恰好定位在轴的右上角,以便图例的边缘和轴的边缘之间没有微小的线条部分。我想通过直接调用 Legend 对象的方法来完成此操作,例如

Legend.set_bbox_to_anchor()

,但我的尝试似乎根本没有移动图例。

这是我最近的尝试:

leg.set_bbox_to_anchor((1,1), transform = ax.transAxes)

其中

leg

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

python matplotlib legend
2个回答
5
投票
尝试

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


0
投票
以下是如何微调图例位置的简单示例:

# Get legend leg = ax.legend(loc='lower left') # Reposition it using axes relative coordinates (0...1, 0...1) leg.set_bbox_to_anchor((0.250, 0.11, 0.3, 0.5), transform=ax.transAxes)
    
© www.soinside.com 2019 - 2024. All rights reserved.