Franck Dernoncourt
Franck Dernoncourt

Reputation: 83177

Centering a legend title with line breaks in matplotlib

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()

enter image description here

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()

enter image description here

but that's a cumbersome solution.

Is there any more proper way to achieve that?

Upvotes: 12

Views: 6476

Answers (1)

Andi
Andi

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

Related Questions