Reputation: 83177
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?
Upvotes: 12
Views: 6476
Reputation: 1273
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')
Upvotes: 17