Matplotlib图例中的文本对齐方式

2024-04-26 13:51:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图右对齐matplotlib轴图例中的条目(默认情况下它们是左对齐的),但似乎找不到任何方法来执行此操作。我的设置如下:

(我已使用ax.plot()命令将数据和标签添加到我的图形轴)

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

文档中有一个matplotlib Axes的图例关键字参数列表,但似乎没有任何straighforward方法来设置图例项的对齐方式。有人知道这种后门的做法吗?谢谢。

编辑:

为了澄清我想达到的目标,现在我的传说是:

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

Tags: 方法命令plotmatplotlib情况条目axoct
2条回答

我试着做这个例子,但做不到

至少自从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))

你要找的后门如下:

# 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))

相关问题 更多 >