Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: alignment of legend title

Tags:

matplotlib

In matplotlib, how can I adjust the alignment of the legend title? It is always centered, but I need it to be left aligned with the legend box. I tried to change the alignment of the title's Text artist which has no effect. See the following example for details:

from pylab import *  x = linspace(0, 1) plot(x, x, label="1") plot(x, x**2, label="2") plot(x, x**3, label="3") plot(x, sqrt(x), label="square root")  l = legend(title="Title", loc="best") l.get_title().set_ha("left")               # <== does not work  show() 

The question boils down to what and who controls the anchor point of the title alignment? Changing the alignment to "right" or "center" has a noticeable effect. Second observation: for long title strings the anchor point moves to the left border of the legend box ...

like image 549
Erwin411 Avatar asked Mar 26 '13 13:03

Erwin411


People also ask

How do I align a legend in Matplotlib?

MatPlotLib with Python Plot line1 and line2 using plot() method. Place a legend on the figure. Use bbox_to_anchor to set the position and make horizontal alignment of the legend elements. To display the figure, use show() method.

How do I change the legend position in Matplotlib?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.

How do I make the legend horizontal in Matplotlib?

Set the figure size and adjust the padding between and around the subplots. Using plot() method, plot lines with the labels line1, line2 and line3. Place a legend on the figure using legend() method, with number of labels for ncol value in the argument.


2 Answers

You may align the complete legend box setting leg._legend_box.align. This aligns everything inside the legend box, but the effect is the desired one to have the title on either side of the box instead of the center.

  • Left aligned

    leg = plt.legend(title="Title") leg._legend_box.align = "left" 

    enter image description here

  • Right aligned

    leg = plt.legend(title="Title") leg._legend_box.align = "right" 

    enter image description here

like image 138
ImportanceOfBeingErnest Avatar answered Oct 04 '22 12:10

ImportanceOfBeingErnest


I think you need to displace the Text object, using the set_position((x, y)) method. The units of x and y are pixels, so you'll have to experiment with what values look right, or use a Transform. I'm not sure off hand which combination of Transforms might be most useful.

So in short, something like this might work:

l.get_title().set_position((-10, 0)) # -10 is a guess 
like image 33
Yann Avatar answered Oct 04 '22 11:10

Yann