简体   繁体   English

Matplotlib图例中的文本对齐方式

[英]Text alignment in a Matplotlib legend

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. 我试图右键对齐matplotlib轴图例中的条目(默认情况下它们是左对齐的),但似乎无法找到任何方法。 The setup I have is below: 我的设置如下:

(I have added data and labels to my_fig axes using the ax.plot() command) (我使用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)

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. matplotlib Axes的文档中有一个图例关键字参数列表,但似乎没有任何直接的方法来设置图例条目的对齐方式。 Anybody know of a backdoor way of doing this? 有人知道这样做的后门方式吗? Thanks. 谢谢。

EDIT: 编辑:

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 

I want it to look like: 我希望它看起来像:

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

I tried to get the example work, but I couldn't. 我试图让示例工作,但我不能。

At least since matplotlib version 1.1.1 (maybe earlier) we need a dedicated renderer instance. 至少从matplotlib版本1.1.1(可能更早)开始,我们需要一个专用的渲染器实例。 Take care of your backend which defines the renderer. 请注意定义渲染器的后端。 Depending on backend the output may look fine on screen but dismal as PDF. 根据后端,输出可能在屏幕上看起来很好,但是像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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM