Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib savefig with a legend outside the plot

Reading the following article, I managed to put a legend outside plot.

  • How to put the legend out of the plot

code:

import matplotlib.pyplot as pyplot  x = [0, 1, 2, 3, 4] y = [xx*xx for xx in x]  fig = pyplot.figure() ax  = fig.add_subplot(111)  box = ax.get_position() ax.set_position([box.x0, box.y0, box.width*0.8, box.height])  ax.plot(x, y) leg = ax.legend(['abc'], loc = 'center left', bbox_to_anchor = (1.0, 0.5)) #pyplot.show()  fig.savefig('aaa.png', bbox_inches='tight') 

pyplot.show() displays the correct plot with a legend outside it. But when I save it as a file with fig.savefig(), the legend is truncated.

Some googling shows me workarounds such as adding bbox_extra_artists=[leg.legendPatch] or bbox_extra_artists=[leg] to savefig(), but neither worked.

What is the correct way to do it? Matplotlib version is 0.99.3.

Thanks.

like image 643
niboshi Avatar asked Jan 23 '12 12:01

niboshi


People also ask

How do I move the legend outside of a plot 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.

How do you add a legend to the outside of a chart?

To place the legend outside of the axes bounding box, one may specify a tuple (x0, y0) of axes coordinates of the lower left corner of the legend. places the legend outside the axes, such that the upper left corner of the legend is at position (1.04, 1) in axes coordinates.

How do I control the location 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.


1 Answers

The problem is that when you plot dynamically, matplotlib determines the borders automatically to fit all your objects. When you save a file, things are not being done automatically, so you need to specify the size of your figure, and then the bounding box of your axes object. Here is how to correct your code:

import matplotlib.pyplot as pyplot  x = [0, 1, 2, 3, 4] y = [xx*xx for xx in x]  fig = pyplot.figure(figsize=(3,3)) ax  = fig.add_subplot(111)  #box = ax.get_position() #ax.set_position([0.3, 0.4, box.width*0.3, box.height]) # you can set the position manually, with setting left,buttom, witdh, hight of the axis # object ax.set_position([0.1,0.1,0.5,0.8]) ax.plot(x, y) leg = ax.legend(['abc'], loc = 'center left', bbox_to_anchor = (1.0, 0.5))  fig.savefig('aaa.png') 
like image 153
oz123 Avatar answered Sep 22 '22 21:09

oz123