Matplotlib图例中的文本对齐

25 投票
3 回答
23496 浏览
提问于 2025-04-17 05:13

我想把matplotlib图例中的条目右对齐(默认是左对齐),但我找不到任何方法来做到这一点。下面是我的设置:

(我已经通过ax.plot()命令给my_fig的坐标轴添加了数据和标签)

ax = my_fig.get_axes()[0]
legend_font = FontProperties(size=10)
ax.legend(prop=legend_font, num_points=1, markerscale=0.5)

matplotlib Axes的文档中,有一份图例关键字参数的列表,但似乎没有简单的方法可以设置图例条目的对齐方式。有没有人知道有什么变通的方法可以做到这一点?谢谢。

编辑:

为了更清楚我想要达到的效果,现在我的图例看起来是:

Maneuver: 12-OCT-2011 12:00 UTC 

Bias: 14-OCT-2011 06:00 UTC

我希望它看起来像这样:

Maneuver: 12-OCT-2011 12:00 UTC 

    Bias: 14-OCT-2011 06:00 UTC

3 个回答

4

@Paul Ivanov 的回答让我找到了正确的方向。不过我需要稍微调整一下:

max_shift = max([t.get_window_extent().width for t in legend_obj.get_texts()])
for t in legend_obj.get_texts():
    t.set_ha('right')  # ha is alias for horizontalalignment
    temp_shift = max_shift - t.get_window_extent().width
    t.set_position((temp_shift, 0))

这个改变的意思是,我们根据每个对象的宽度和图例文本的最大宽度,设置了不同的偏移量。

如果你遇到 Cannot get window extent w/o renderer 这个错误,可以加上 plt.pause(0.1) 来解决哦 :)

27

我试着让这个例子运行起来,但没成功。

从matplotlib版本1.1.1开始(可能更早),我们需要一个专门的渲染器实例。要注意你的后端设置,因为它决定了渲染器的类型。根据不同的后端,输出在屏幕上可能看起来不错,但在PDF中可能就很糟糕。

# get the width of your widest label, since every label will need 
#to shift by this amount after we align to the right
renderer = figure.canvas.get_renderer()
shift = max([t.get_window_extent(renderer).width for t in legend.get_texts()])
for t in legend.get_texts():
    t.set_ha('right') # ha is alias for horizontalalignment
    t.set_position((shift,0))
30

你要找的后门代码如下:

# get the width of your widest label, since every label will need 
# to shift by this amount after we align to the right
shift = max([t.get_window_extent().width for t in legend.get_texts()])
for t in legend.get_texts():
    t.set_ha('right') # ha is alias for horizontalalignment
    t.set_position((shift,0))

撰写回答