Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

python - 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. The setup I have is below:

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

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.

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...