How can I place the legend outside of a plot in Matplotlib?

The process of placing the legend outside of a plot in Matplotlib involves using the “bbox_to_anchor” parameter to specify the location of the legend relative to the plot. This can be achieved by providing specific coordinates or using predefined values such as “upper right”, “lower left”, etc. Additionally, the “loc” parameter can be used to further adjust the positioning of the legend. With these parameters, the legend can be easily placed outside of the plot area, providing a more organized and visually appealing representation of the data.

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

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

The following tutorials explain how to perform other common tasks in Matplotlib:

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

x