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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github