Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to put legend title at left?

Tags:

matplotlib

The following code creates a legend with a title.

from pylab import *
plt.plot([1,2],[2,3],label='sdfsdf')
legend(title='s') 

output picture here

's' is located at the center of the legend.
I wonder how to put 's' to the left side.

like image 730
weiwei Avatar asked Jan 26 '26 10:01

weiwei


1 Answers

The easiest option would probably be to add a lot of whitespace behind the title

import matplotlib.pyplot as plt
plt.plot([1,2],[2,3],label='sdfsdf')
plt.legend(title='s                ')
plt.show()

enter image description here

The drawback of this is of course that the amount of whitespace depends on the legend size.

The other option is therefore to change the alignment within the legend, using ._legend_box.align.

import matplotlib.pyplot as plt
plt.plot([1,2],[2,3],label='sdfsdf')
leg = plt.legend(title='s')
leg._legend_box.align = "left"

plt.show()

enter image description here

Note that this is the aligment of all the legend entries, as there is unfortunately no way to align the title independently. In most cases it will not matter, but one has to be aware of that if unforeseen issues arise with more complex legends (multicolumn etc.).

like image 140
ImportanceOfBeingErnest Avatar answered Jan 29 '26 13:01

ImportanceOfBeingErnest