Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to add legend in matplotlib

Understanding Legends in Data Visualization

When you look at a map, a legend is a small box that helps you understand the symbols, colors, and lines used on the map. Similarly, in data visualization, a legend is a guide for deciphering the different elements of a chart or graph. In the world of programming, especially when you're dealing with plotting libraries like Matplotlib, adding a legend to your plots can greatly enhance the readability and understanding of your data.

The Basics of Matplotlib Legends

Matplotlib is a popular plotting library for Python that lets you create a wide range of static, interactive, and animated visualizations. Legends in Matplotlib serve as an essential tool to label different data series represented by various colors, markers, or line styles within a single plot.

Imagine you're looking at a garden with a variety of flowers. Each type of flower has a unique color. If someone gave you a chart showing colors and corresponding flower names, you’d have an easier time identifying each flower. That's what a legend does for your plot.

Adding a Legend with plt.legend()

To add a legend to your Matplotlib plot, you can use the plt.legend() function. Let's start with a simple example:

import matplotlib.pyplot as plt

# Data for plotting
x = [1, 2, 3, 4]
y1 = [10, 20, 25, 30]
y2 = [40, 35, 30, 20]

# Plotting two lines
plt.plot(x, y1, label='Product A Sales')
plt.plot(x, y2, label='Product B Sales')

# Adding a legend
plt.legend()

# Display the plot
plt.show()

In this code, we have two sets of data representing sales of two different products. We plot both sets of data with lines on the same graph. By calling plt.legend(), we create a legend that uses the labels 'Product A Sales' and 'Product B Sales' that we defined in the plot() function.

Customizing Your Legend

Positioning the Legend

Sometimes, the default position of the legend might overlap with your data. To prevent this, you can specify the location of your legend using the loc parameter:

# Adding a legend with a specific location
plt.legend(loc='upper left')

The loc parameter accepts location strings like 'upper right', 'lower left', 'center', 'best', and more. The option 'best' lets Matplotlib decide the best location to avoid covering the data.

Changing the Number of Columns

If you have many items in your legend, you might want to organize them in columns. You can do this using the ncol parameter:

# Organizing legend items into two columns
plt.legend(ncol=2)

Setting the Font Size

To change the font size of the text in the legend, use the fontsize parameter:

# Setting the font size of the legend
plt.legend(fontsize='small')

You can specify standard font size names like 'small', 'medium', 'large', or you can use a numeric value for a specific size.

Adding a Frame

A frame or border can help your legend stand out. You can add a frame using the frameon parameter:

# Adding a frame to the legend
plt.legend(frameon=True)

By default, frameon is True, but you can set it to False if you want to remove the frame.

Legends with Multiple Plots

Sometimes, you might be working with subplots—separate sections within the same figure, each with its own plot. You can add legends to individual subplots just as you would with a single plot:

# Creating subplots
fig, (ax1, ax2) = plt.subplots(1, 2)

# Plotting on the first subplot
ax1.plot(x, y1, label='First')
ax1.legend()

# Plotting on the second subplot
ax2.plot(x, y2, label='Second')
ax2.legend()

# Display the figure with subplots
plt.show()

Each subplot (ax1 and ax2) has its own plot and corresponding legend.

Handling Complex Legends

When you have complex data, such as multiple lines with different markers and line styles, you can still manage your legend effectively. Let's look at a more complex example:

# Plotting with different styles
plt.plot(x, y1, 'r-o', label='Red Circle')
plt.plot(x, y2, 'g--s', label='Green Dashed Square')

# Adding a legend with a title
plt.legend(title='Legend Title')

# Display the plot
plt.show()

Here, 'r-o' creates a red line with circle markers, and 'g--s' creates a green dashed line with square markers. The title parameter adds a title to the legend for additional clarity.

Intuitive Understanding of Legend Placement

Think of placing a legend like parking a car in a crowded lot. You want to find a spot where the car won't block traffic or take up too much space. Similarly, when placing a legend, you want to find a location that doesn't cover your data (the "traffic") and fits neatly within the plot (the "parking lot").

Conclusion

Adding a legend to your Matplotlib plots is like giving your audience a key to unlock the meaning behind the colors and shapes they see. It's a simple yet powerful tool that can turn a confusing graph into an insightful story. Remember, the goal is to make your data as clear and accessible as possible, much like a well-organized book where the reader can easily find the chapter they're looking for. With the techniques you've learned today, you're now equipped to create legends that not only inform but also enhance the visual appeal of your data stories. So go ahead, plot your data, and let your legends guide your audience through the fascinating tales hidden within the numbers.