Home Content Positioning a legend outside the figure with Matplotlib and Python

Positioning a legend outside the figure with Matplotlib and Python

by Jack Simpson

One of the things that has been a little frustrating lately has been what to do if you need a legend for your plot, yet there’s so much content on your plot you need to place it next to the figure, rather than within it.  The standard way to create a plot with the legend within it looks like this:

Standard Legend

import matplotlib.pyplot as plt
import numpy as np

plt.figure()
plt.plot([5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], '-go', label='bottom_right_section')
plt.xlim([0,39])
plt.title('Bee Speed By Quarter of Frame')
plt.xlabel("Nights and Days")
plt.ylabel("Number of fast cells")
plt.legend(loc='upper left')
plt.show()

The first step I tried to move the legend outside the figure was to add this code to the “legend” method:

plt.legend(loc='upper left', bbox_to_anchor=(1,1)) 

bbox_test

Unfortunately, the legend was being cut-off on the right hand side. I then tried to shrink down the legend (as it was rather large) and when that didn’t work, I found out that I could pass a padding argument to the “tight_layout” method which finally solved the issue:

plt.legend(loc='upper left', prop={'size':6}, bbox_to_anchor=(1,1))
plt.tight_layout(pad=7)

matplotlib_padding

The final code to solve the problem with establishing a large margin around the figure:


import matplotlib.pyplot as plt
import numpy as np

plt.figure()
plt.plot([5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5], '-go', label='bottom_right_section')
plt.xlim([0,39])
plt.title('Bee Speed By Quarter of Frame')
plt.xlabel("Nights and Days")
plt.ylabel("Number of fast cells")
plt.legend(loc='upper left', prop={'size':6}, bbox_to_anchor=(1,1))
plt.tight_layout(pad=7)
plt.show()

Sign up to my newsletter

Sign up to receive the latest articles straight to your inbox

You may also like

Leave a Comment