When you create plots with multiple lines, colors, markers, or styles representing different categories or datasets, a legend becomes essential. It acts as a key, explaining what each visual element signifies. Matplotlib and Seaborn often generate legends automatically when you provide labels for your plotted data, but you frequently need to adjust their position, appearance, or content for maximum clarity.
The simplest way to get a legend is by adding a label
argument to your plotting commands. Matplotlib keeps track of these labels and can display them when instructed.
Consider plotting two lines:
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Create plot using the functional API
plt.figure(figsize=(6, 4))
plt.plot(x, y1, label='Sine Wave')
plt.plot(x, y2, label='Cosine Wave', linestyle='--')
plt.title('Sine and Cosine Waves')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Instruct Matplotlib to display the legend
plt.legend()
plt.show()
In this script, we provided the label
argument within each plt.plot()
call. The final plt.legend()
command tells Matplotlib to gather all defined labels and display them in a legend box. If you are using the object-oriented approach with Axes objects, you would call ax.legend()
instead of plt.legend()
.
Matplotlib tries to find the "best" location for the legend automatically (loc='best'
) to minimize overlap with the plotted data. However, this automatic placement might not always be ideal. You can explicitly control the legend's position using the loc
argument within the legend()
function.
Common loc
values include:
'best'
(default)'upper right'
'upper left'
'lower left'
'lower right'
'right'
'center left'
'center right'
'lower center'
'upper center'
'center'
Let's modify the previous example to place the legend in the lower left corner:
# ... (previous setup code for x, y1, y2)
plt.figure(figsize=(6, 4))
plt.plot(x, y1, label='Sine Wave')
plt.plot(x, y2, label='Cosine Wave', linestyle='--')
plt.title('Sine and Cosine Waves')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Place the legend in the lower left
plt.legend(loc='lower left')
plt.show()
Experimenting with different loc
values helps find the most suitable position for your specific plot, ensuring the legend doesn't obscure important data points or trends.
For more precise control beyond these string codes, you can use the bbox_to_anchor
argument, which allows specifying coordinates relative to the axes or figure. This is more advanced and often not needed for basic plots, but useful for complex layouts.
Beyond placement, you can modify the legend's appearance:
title
argument.ncol
. This is useful for legends with many items.frameon=False
.fontsize
.Here’s an example applying some of these customizations:
# ... (previous setup code for x, y1, y2)
plt.figure(figsize=(7, 5)) # Slightly larger figure
plt.plot(x, y1, label='Sine')
plt.plot(x, y2, label='Cosine', linestyle='--')
plt.plot(x, y1*0.5, label='Sine/2', linestyle=':')
plt.plot(x, y2*0.5, label='Cosine/2', linestyle='-.')
plt.title('Multiple Trigonometric Functions')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Customize the legend
plt.legend(loc='upper center', ncol=2, title='Functions', frameon=False, fontsize='small')
plt.show()
This places the legend at the top center, arranges the four items into two columns, adds a title "Functions", removes the frame, and uses a slightly smaller font.
Seaborn integrates tightly with Matplotlib and often handles legends automatically, especially when using parameters like hue
, size
, or style
to differentiate data. Seaborn typically places the legend outside the plot area if it anticipates overlap.
import seaborn as sns
import pandas as pd
# Create a DataFrame suitable for Seaborn
data = pd.DataFrame({
'x': np.tile(x, 2),
'y': np.concatenate([y1, y2]),
'type': ['Sine Wave'] * len(x) + ['Cosine Wave'] * len(x)
})
plt.figure(figsize=(6, 4))
# Seaborn automatically creates a legend based on 'hue'
sns.lineplot(data=data, x='x', y='y', hue='type')
plt.title('Seaborn Plot with Automatic Legend')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# We can still access the Matplotlib Axes to potentially modify the legend later if needed
# ax = plt.gca() # Get current Axes
# ax.legend(loc='lower left') # Example: Move the Seaborn-generated legend
plt.show()
Even when Seaborn creates the legend, you can often use Matplotlib's ax.legend()
(after getting the Axes object, for instance via ax = sns.lineplot(...)
or ax = plt.gca()
) to modify its properties like location, title, or frame visibility, just as you would for a pure Matplotlib plot.
Managing legends effectively is an important part of creating clear and understandable visualizations. By using labels correctly and knowing how to adjust the legend's position and basic appearance, you can ensure your audience can easily interpret the different elements within your plots.
© 2025 ApX Machine Learning