Matplotlib图例中的文本对齐 [英] Text alignment in a Matplotlib legend
问题描述
我正在尝试使matplotlib轴图例中的条目右对齐(默认情况下它们左对齐),但是似乎找不到任何方法.我的设置如下:
I am trying to right-align the entries in a matplotlib axes legend (by default they are left-aligned), but can't seem to find any way of doing this. The setup I have is below:
(我已经使用ax.plot()命令向my_fig轴添加了数据和标签)
(I have added data and labels to my_fig axes using the ax.plot() command)
ax = my_fig.get_axes()[0]
legend_font = FontProperties(size=10)
ax.legend(prop=legend_font, num_points=1, markerscale=0.5)
文档中有 matplotlib轴的图例关键字参数列表,但是似乎没有任何简单的方法可以在那里设置图例条目的对齐方式.有人知道这样做的后门方式吗?谢谢.
There is a list of legend keyword arguments in the docs for matplotlib Axes, but there doesn't seem to be any straighforward way to set the alignment of the legend entries there. Anybody know of a backdoor way of doing this? Thanks.
为了阐明我要实现的目标,现在我的传说如下:
To clarify what I am trying to achieve, right now my legend looks like:
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
推荐答案
您正在寻找的后门如下:
The backdoor you're looking for is the following:
# 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))
这篇关于Matplotlib图例中的文本对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!