How to Put the Legend outside the Plot

Better Stack Team
Updated on June 19, 2024

To put the legend outside the plot in Matplotlib, you can use the bbox_to_anchor parameter of the plt.legend() function along with the loc parameter to specify the location outside the plot area. Here's how you can do it:

 
import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [1, 2, 3, 4, 5]

# Plot the data
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')

# Place the legend outside the plot
plt.legend(loc='upper left', bbox_to_anchor=(1, 1))

# Show the plot
plt.show()

In this example, bbox_to_anchor=(1, 1) specifies the position of the legend relative to the plot area. (1, 1) places the legend in the upper-right corner outside the plot area. You can adjust these coordinates to position the legend wherever you like outside the plot. Adjusting the loc parameter allows you to specify the anchor point within the legend box.

By setting bbox_to_anchor=(x, y), you can control the position of the legend outside the plot. The loc parameter determines where the legend box is anchored relative to the specified position.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.