How to Place the Legend Outside of a Matplotlib Plot


Often you may want to place the legend of a Matplotlib plot outside of the actual plot. Fortunately this is easy to do using the matplotlib.pyplot.legend() function combined with the bbox_to_anchor argument.

This tutorial shows several examples of how to use this function in practice.

Example 1: Place Legend in Top Right Corner

The following code shows how to place the legend in the top right corner outside of a Matplotlib plot:

import matplotlib.pyplot as plt

#create plot
plt.subplot(211)
plt.plot([2, 4, 6], label="First Data")
plt.plot([6, 4, 2], label="Second Data")

#place legend in top right corner
plt.legend(bbox_to_anchor=(1,1), loc="upper left")

#show plot
plt.show()

Place legend outside of Matplotlib plot

Note that the loc argument tells Matplotlib to place the upper left corner of the legend line at the (x,y) coordinates of (1,1) in the plot.

Example 2: Place Legend in Bottom Right Corner

The following code shows how to place the legend in the bottom right corner outside of a Matplotlib plot:

import matplotlib.pyplot as plt

#create plot
plt.subplot(211)
plt.plot([2, 4, 6], label="First Data")
plt.plot([6, 4, 2], label="Second Data")

#place legend in top right corner
plt.legend(bbox_to_anchor=(1,0), loc="lower left")

#show plot
plt.show()

Legend outside of Matplotlib plot in corner

Note that the loc argument tells Matplotlib to place the lower left corner of the legend line at the (x,y) coordinates of (1,0) in the plot.

Example 3: Place Legend Above Plot

The following code shows how to place the legend above the Matplotlib plot:

import matplotlib.pyplot as plt

#create plot
plt.subplot(211)
plt.plot([2, 4, 6], label="First Data")
plt.plot([6, 4, 2], label="Second Data")

#place legend above plot
plt.legend(bbox_to_anchor=(0, 1, 1, 0), loc="lower left", mode="expand", ncol=2)

#show plot
plt.show()

Place legend above plot in Matplotlib

Note that the mode argument tells Matplotlib to expand the legend to the length of the plot and the ncol argument tells Matplotlib to place the legend labels in 2 columns.

We could also leave out the mode and ncol arguments if we simply want to place the legend in the top left corner above the plot:

Additional Resources

How to Change Font Sizes on a Matplotlib Plot
How to Remove Ticks from Matplotlib Plots
How to Show Gridlines on Matplotlib Plots

Leave a Reply

Your email address will not be published. Required fields are marked *