Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to move legend outside plot in matplotlib

Understanding Legends in Matplotlib

When you're new to programming and data visualization, you might find yourself creating plots and charts that require a legend to help explain what's being shown. In Matplotlib, which is a plotting library for Python, legends are used to describe the elements of the plot. Think of a legend as a guide or a key to a map that helps you understand which symbol or color corresponds to which data series.

Adding a Basic Legend

Before we move the legend outside the plot, let's first understand how to create a basic legend inside the plot. Here's a simple code example:

import matplotlib.pyplot as plt

# Some sample data
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [2, 3, 6, 8, 10]

# Plotting the data
plt.plot(x, y1, label='Squared Numbers')
plt.plot(x, y2, label='Multiplied by 2')

# Adding a legend
plt.legend()

# Display the plot
plt.show()

In this example, we have two sets of data: one represents squared numbers and the other is simply each number in x multiplied by two. We use plt.plot() to plot these data sets and give them labels. Then, we call plt.legend() to automatically generate a legend based on the labels we've provided.

Moving the Legend Outside the Plot

Sometimes, the legend might overlap with your data, making the plot hard to read. Luckily, Matplotlib provides a way to move the legend outside the plot. Let's see how to do that with an example:

import matplotlib.pyplot as plt

# Using the same data as before
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [2, 3, 6, 8, 10]

# Plotting the data
plt.plot(x, y1, label='Squared Numbers')
plt.plot(x, y2, label='Multiplied by 2')

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

# Display the plot
plt.show()

Here, we've introduced two new parameters to the plt.legend() function: loc and bbox_to_anchor. The loc parameter specifies the anchor point for the legend. In this case, 'upper left' means the upper left corner of the legend box. The bbox_to_anchor parameter is a tuple of two values that moves the legend box to a specific position. The values (1, 1) move the legend box so that its upper left corner is just outside the upper right corner of the plot.

Fine-Tuning the Legend Placement

You might want to adjust the placement of the legend further to make sure it doesn't cut off or overlap with other elements of your figure. You can do this by tweaking the values in bbox_to_anchor. Here's an example:

import matplotlib.pyplot as plt

# Using the same data as before
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [2, 3, 6, 8, 10]

# Plotting the data
plt.plot(x, y1, label='Squared Numbers')
plt.plot(x, y2, label='Multiplied by 2')

# Adjusting the legend's position
plt.legend(loc='upper left', bbox_to_anchor=(1.05, 1))

# Display the plot
plt.show()

In this case, we've changed the bbox_to_anchor to (1.05, 1), which moves the legend slightly further to the right, ensuring it doesn't overlap with the plot.

Adding a Frame and Title to the Legend

To make your legend stand out and improve readability, you can add a frame around it and even include a title. Here's how you can do that:

import matplotlib.pyplot as plt

# Using the same data as before
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [2, 3, 6, 8, 10]

# Plotting the data
plt.plot(x, y1, label='Squared Numbers')
plt.plot(x, y2, label='Multiplied by 2')

# Adding a frame and title to the legend
plt.legend(loc='upper left', bbox_to_anchor=(1.05, 1), frameon=True, title='Legend')

# Display the plot
plt.show()

The frameon=True parameter tells Matplotlib to draw a frame around the legend. The title='Legend' parameter adds a title to the legend box.

Handling Overlapping with the Figure

Even after moving the legend outside, you might find that the legend is getting cut off because the figure size isn't large enough to accommodate it. To fix this, you can resize the figure using plt.figure() before plotting your data:

import matplotlib.pyplot as plt

# Set the figure size to avoid cutting off the legend
plt.figure(figsize=(10, 5))

# Using the same data as before
x = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
y2 = [2, 3, 6, 8, 10]

# Plotting the data
plt.plot(x, y1, label='Squared Numbers')
plt.plot(x, y2, label='Multiplied by 2')

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

# Display the plot
plt.show()

By setting the figsize parameter in plt.figure(), you can control the width and height of the figure in inches. This gives you more space to fit the legend outside the plot without it getting cut off.

Conclusion

Matplotlib gives you the flexibility to create and customize legends for your plots. Moving the legend outside the plot is a simple yet powerful way to enhance the clarity and readability of your visualizations. With the skills you've learned here, you can ensure that the legends in your plots serve as helpful guides rather than obstacles. Keep experimenting with the different parameters, and you'll soon find the perfect spot for your legends that complements your data visualizations. Remember, a well-placed legend is like a compass on a map—it doesn't take up too much space but provides valuable direction to help you navigate through the data. Happy plotting!