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:
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.
To place a legend on the figure and to adjust the size of legend box, use borderpad=2 in legend() method.
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.
Eventhough that it is late, I want to refer to a nice recently introduced alternative:
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')
I want to refer also to a more detailed answer: Moving matplotlib legend outside of the axis makes it cutoff by the figure box
plt.subplots
as-well where as the others are not!If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With