Legends in Matplotlib
Learn how to add legends to Matplotlib charts, identify multiple data series, customize legend positions, and improve the readability of your visualizations.
1. Learning Objectives
After completing this lesson, you will be able to:
- Understand what a legend is in Matplotlib.
- Add legends using the
legend()function. - Assign labels to multiple data series.
- Change the position of a legend.
- Customize legend font size, title, and frame.
- Display legends outside the plotting area.
- Control legend entries using handles and labels.
2. Introduction to Legends
A legend is a small box displayed inside or outside a chart that explains what each line, marker, or data series represents.
When a chart contains multiple lines or categories, it may be difficult to identify which data belongs to which series. Legends solve this problem by displaying meaningful labels.
Example Scenario
Suppose you want to compare the monthly sales of three products: Laptop, Mobile, and Tablet. A legend helps users identify each product's line in the chart.
Basic Syntax
plt.legend()
The legend() function displays the legend using labels
assigned to the plotted data.
3. Adding a Basic Legend
To display a legend, first provide a label parameter
when creating a plot. Then call plt.legend().
Example: Basic Line Chart with Legend
import matplotlib.pyplot as plt
months = [1, 2, 3, 4, 5, 6]
sales = [100, 150, 130, 180, 200, 220]
plt.plot(months, sales, label="Product A")
plt.title("Monthly Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.show()
Expected Output
Chart Title: Monthly Sales
X-axis: Month
Y-axis: Sales
Line:
Product A
Legend:
Product A
A legend box appears inside the chart.
4. Legends for Multiple Data Series
When a chart contains multiple data series, assign a different label to each series. Matplotlib uses these labels to create separate legend entries.
Example: Comparing Multiple Products
import matplotlib.pyplot as plt
months = [1, 2, 3, 4, 5, 6]
laptop = [100, 120, 150, 170, 190, 220]
mobile = [80, 100, 130, 140, 180, 200]
tablet = [50, 70, 90, 110, 120, 150]
plt.plot(months, laptop, label="Laptop")
plt.plot(months, mobile, label="Mobile")
plt.plot(months, tablet, label="Tablet")
plt.title("Product Sales Comparison")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.show()
Expected Output
Chart Title: Product Sales Comparison
X-axis: Month
Y-axis: Sales
Three data series:
1. Laptop
2. Mobile
3. Tablet
Legend Entries:
Laptop
Mobile
Tablet
Each legend entry identifies its corresponding data series. This makes the chart easier to understand.
5. Changing Legend Position
Matplotlib provides the loc parameter to control
where the legend appears in the chart.
Common Legend Positions
| Location Value | Position |
|---|---|
best |
Automatically selects the best position. |
upper right |
Top-right corner. |
upper left |
Top-left corner. |
lower right |
Bottom-right corner. |
lower left |
Bottom-left corner. |
center |
Center of the chart. |
center left |
Center-left position. |
center right |
Center-right position. |
upper center |
Top-center position. |
lower center |
Bottom-center position. |
Example: Legend at Upper Right
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 30, 40, 50]
y2 = [15, 25, 35, 45, 55]
plt.plot(x, y1, label="Series A")
plt.plot(x, y2, label="Series B")
plt.title("Legend Position Example")
plt.legend(loc="upper right")
plt.show()
Expected Output
Chart Title: Legend Position Example
Legend Position:
Upper Right
Legend Entries:
Series A
Series B
loc="best" when you want
Matplotlib to automatically select a suitable position.
6. Customizing Legends
Matplotlib allows you to customize legends using different parameters such as font size, title, frame, and marker appearance.
Important Legend Parameters
| Parameter | Description |
|---|---|
loc |
Sets the legend position. |
fontsize |
Changes the legend text size. |
title |
Adds a title to the legend. |
frameon |
Shows or hides the legend frame. |
ncol |
Sets the number of columns. |
markerscale |
Changes the marker size inside the legend. |
labelspacing |
Controls vertical spacing between entries. |
borderpad |
Controls padding inside the legend border. |
Example: Customized Legend
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 30, 40, 50]
y2 = [15, 25, 35, 45, 55]
plt.plot(x, y1, label="Sales")
plt.plot(x, y2, label="Revenue")
plt.title("Business Performance")
plt.xlabel("Month")
plt.ylabel("Amount")
plt.legend(
title="Business Data",
loc="upper left",
fontsize=10,
frameon=True,
ncol=1
)
plt.show()
Expected Output
Chart Title: Business Performance
Legend Title: Business Data
Legend Entries:
Sales
Revenue
Position: Upper Left
Font Size: 10
Frame: Visible
Columns: 1
7. Removing the Legend Frame
By default, a legend is displayed with a frame. You can remove
this frame by setting frameon=False.
Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 25, 30, 45, 50]
plt.plot(x, y, label="Growth")
plt.title("Growth Chart")
plt.legend(frameon=False)
plt.show()
Expected Output
Chart Title: Growth Chart
Legend:
Growth
Legend Frame:
Hidden
The legend text is displayed without a surrounding box.
8. Displaying Legends Outside the Chart
Sometimes a chart contains many data series. In that situation, placing the legend outside the plotting area can improve readability.
The bbox_to_anchor parameter helps position the
legend relative to the chart.
Example: External Legend
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 30, 40, 50]
y2 = [15, 25, 35, 45, 55]
y3 = [20, 30, 40, 50, 60]
plt.plot(x, y1, label="Product A")
plt.plot(x, y2, label="Product B")
plt.plot(x, y3, label="Product C")
plt.title("Product Comparison")
plt.legend(
loc="upper left",
bbox_to_anchor=(1, 1)
)
plt.tight_layout()
plt.show()
Expected Output
Chart Title: Product Comparison
Chart:
Three product data series
External Legend:
Product A
Product B
Product C
Legend Position:
Outside the right side of the plotting area.
plt.tight_layout() to help manage the
available figure space. For saved figures, you may also need
bbox_inches="tight".
9. Using Handles and Labels
Matplotlib allows you to control legend entries manually using handles and labels. This is useful when you want to customize which plotted objects appear in the legend.
Example
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
line1, = plt.plot(x, [10, 20, 30, 40, 50])
line2, = plt.plot(x, [15, 25, 35, 45, 55])
plt.legend(
handles=[line1, line2],
labels=["First Series", "Second Series"]
)
plt.title("Manual Legend Example")
plt.show()
Expected Output
Chart Title: Manual Legend Example
Legend Entries:
First Series
Second Series
Both entries are associated with their respective plotted lines.
10. Creating Legends with the Object-Oriented API
Matplotlib also supports legends through the object-oriented API.
Instead of using plt.legend(), you can call
ax.legend() on the Axes object.
Example
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
ax.plot(x, [10, 20, 30, 40, 50], label="Temperature")
ax.plot(x, [15, 25, 35, 45, 55], label="Humidity")
ax.set_title("Weather Information")
ax.set_xlabel("Day")
ax.set_ylabel("Value")
ax.legend(
title="Weather Data",
loc="upper left"
)
plt.show()
Expected Output
Figure:
Weather Information
Axes:
X-axis: Day
Y-axis: Value
Legend Title:
Weather Data
Legend Entries:
Temperature
Humidity
The object-oriented approach is especially useful when working with multiple Axes and complex figures.
11. Practical Activity
Task: Create a Student Performance Chart
Create a line chart to compare the marks of three students across five subjects.
Given Data:
subjects = ["Maths", "Science", "English", "Java", "Python"]
student_a = [85, 90, 78, 92, 88]
student_b = [75, 82, 80, 85, 90]
student_c = [90, 88, 92, 86, 95]
Requirements:
- Create a line chart for all three students.
- Assign a meaningful label to each student.
- Add a chart title.
- Add X-axis and Y-axis labels.
- Display the legend at the upper-left position.
- Add a legend title named Student Details.
12. Practice Questions
- What is a legend in Matplotlib?
- Which function is used to display a legend?
- Why do we use the label parameter in plot()?
- How can you position a legend in the upper-right corner?
- Which parameter removes the legend frame?
- What is the purpose of bbox_to_anchor?
- How can you add a title to a legend?
- What is the difference between plt.legend() and ax.legend()?
- How can you display multiple legend entries in columns?
- When should you use handles and labels?
13. Lesson Summary
In this lesson, you learned how to create and customize legends in Matplotlib. Legends help identify multiple data series and make charts easier to understand.
plt.legend()displays the legend.labelassigns names to plotted data series.loccontrols the legend position.fontsizechanges the legend text size.titleadds a legend heading.frameon=Falsehides the legend frame.ncolcontrols the number of legend columns.bbox_to_anchorhelps position legends outside the chart.ax.legend()creates legends using the Axes object.
You are now ready to use legends to create clear and professional Matplotlib visualizations.