Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering a legend title with line breaks in matplotlib

Tags:

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?

like image 829
Franck Dernoncourt Avatar asked Aug 18 '14 05:08

Franck Dernoncourt


People also ask

How do I align a legend in Matplotlib?

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.

How do I control the position of a legend in Matplotlib?

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.

How do I change the order of items in Matplotlib legend?

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.

How do I move the legend outside in Matplotlib?

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.


1 Answers

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')
like image 108
Andi Avatar answered Oct 18 '22 16:10

Andi