Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My matplotlib.pyplot legend is being cut off

I'm attempting to create a plot with a legend to the side of it using matplotlib. I can see that the plot is being created, but the image bounds do not allow the entire legend to be displayed.

lines = [] ax = plt.subplot(111) for filename in args:     lines.append(plt.plot(y_axis, x_axis, colors[colorcycle], linestyle='steps-pre', label=filename)) ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) 

This produces: enter image description here

like image 582
user1005909 Avatar asked Mar 10 '12 23:03

user1005909


People also ask

How do I fix the legend position 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 legend box size in Matplotlib?

To place a legend on the figure and to adjust the size of legend box, use borderpad=2 in legend() method.

How do you plot a legend outside a plot in Python?

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

Eventhough that it is late, I want to refer to a nice recently introduced alternative:

New matplotlib feature: The tight bounding box

If you are interested in the output file of plt.savefig: in this case the flag bbox_inches='tight' is your friend!

import matplotlib.pyplot as plt  fig = plt.figure(1) plt.plot([1, 2, 3], [1, 0, 1], label='A') plt.plot([1, 2, 3], [1, 2, 2], label='B') plt.legend(loc='center left', bbox_to_anchor=(1, 0))  fig.savefig('samplefigure', bbox_inches='tight') 

Output file: samplefigure.png

I want to refer also to a more detailed answer: Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Advantages

  • There is no need to adjust the actual data/picture.
  • It is compatible with plt.subplots as-well where as the others are not!
  • It applies at least to the mostly used output files, e.g. png, pdf.
like image 106
strpeter Avatar answered Sep 30 '22 18:09

strpeter