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 ...
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.
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.
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.
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"
Right aligned
leg = plt.legend(title="Title") leg._legend_box.align = "right"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With