I use the following code to display a legend title with matplotlib:
import matplotlib.pyplot as plt
# data
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]
# Plot
plt.plot(all_x, all_y)
# Add legend, title and axis labels
plt.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='lower right', title='hello hello hello \n world')
plt.show()
As you can see, "world" is not centered. I would like it to be centered, I can achieve that by manually adding spaces:
import matplotlib.pyplot as plt
# data
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]
# Plot
plt.plot(all_x, all_y)
# Add legend, title and axis labels
plt.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='lower right', title='hello hello hello \n world')
plt.show()
but that's a cumbersome solution.
Is there any more proper way to achieve that?
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.
Change order of items in the legend The above order of elements in the legend region can be changed by the gca method that uses another sub-method called get_legend_handles_labels method. These handles and labels lists are passed as parameters to legend method with order of indexes.
In Matplotlib, to set a legend outside of a plot you have to use the legend() method and pass the bbox_to_anchor attribute to it. We use the bbox_to_anchor=(x,y) attribute. Here x and y specify the coordinates of the legend.
The alignment of multiline matplotlib text is controlled by the keyword argument multialignment
(see here for an example http://matplotlib.org/examples/pylab_examples/multiline.html).
Therefore you can center the title text of the legend as follows:
l = plt.legend(['Lag ' + str(lag) for lag in all_x], loc='lower right',
title='hello hello hello \n world')
plt.setp(l.get_title(), multialignment='center')
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