Reputation: 53923
I've got a plot in matplotlib, which has a lot of lines. I've got a legend which is therefore rather extensive and I placed it next to my plot using the following code:
fontP = FontProperties()
fontP.set_size('small')
plt.legend(variablelist, loc=0, prop = fontP, bbox_to_anchor=(1.0, 1.0))
plt.savefig(filename+'.png')
The result is as follows:
As you can see however, the legend is cut off on the right. Is there a way that I can create more space on the right side of the image so that I can see the full legend?
All tips are welcome!
In response to @mmgp I posted the following code below. As you can see by his answer I forgot to add bbox_inches='tight'
to the savefig part. So for future readers to have a fully working code I just added the bbox_inches='tight'
in the code below, which makes it work perfectly well.. :) :
from random import random
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
mylist = []
for a in range(10):
mylist.append([])
for b in range(10):
mylist[a].append(random())
x = range(len(mylist))
for enum, i in enumerate(mylist):
plt.plot(x, mylist[enum], label='label_'+str(enum))
plt.grid(b=True)
fontP = FontProperties()
fontP.set_size('small')
variablesList = []
for i in range(10):
variablesList.append('label_'+str(i))
legenda = plt.legend(variablesList, loc=0, prop = fontP, bbox_to_anchor=(1.0, 1.0))
plt.savefig('testplot.png', bbox_extra_artists=[legenda], bbox_inches='tight')
Upvotes: 4
Views: 1727
Reputation: 19241
Almost there now, just add a new parameter in savefig
: bbox_inches = 'tight'
. That makes matplotlib figure out the needed size for your plot.
Upvotes: 7