📖 Scenario: You are creating a simple line chart to compare sales data for two products over four quarters. You want to add a legend to explain the lines, but you want to customize the legend entries to use your own labels and colors.
🎯 Goal: Build a line chart with two lines and add a custom legend with your own labels and colors that do not depend on the plotted lines' default labels.
📋 What You'll Learn
Create two lists of sales data for Product A and Product B for four quarters.
Create a list of quarter labels for the x-axis.
Plot the sales data for both products using matplotlib's plot function.
Create a custom legend with exactly two entries using matplotlib.patches.Patch for the legend handles.
Use the custom legend handles and labels in plt.legend().
Display the plot with plt.show().
💡 Why This Matters
🌍 Real World
Custom legends help make charts clearer and more professional, especially when default labels are not descriptive or when you want to highlight specific information.
💼 Career
Data scientists and analysts often customize legends in reports and presentations to improve communication and make visualizations easier to understand.
Progress0 / 4 steps
1
Create sales data and quarter labels
Create a list called quarters with values ["Q1", "Q2", "Q3", "Q4"]. Create two lists called sales_a and sales_b with values [150, 200, 250, 300] and [180, 210, 260, 310] respectively.
Matplotlib
Hint
Use square brackets to create lists with the exact values given.
2
Plot sales data lines
Import matplotlib.pyplot as plt. Use plt.plot() to plot sales_a and sales_b against quarters. Use colors "blue" for sales_a and "green" for sales_b. Do not add labels to the plot lines.
Matplotlib
Hint
Use plt.plot(x, y, color="colorname") to plot lines with specific colors.
3
Create custom legend handles
Import matplotlib.patches.Patch. Create two variables blue_patch and green_patch as Patch objects with colors "blue" and "green" respectively. These will be used as custom legend handles.
Matplotlib
Hint
Use Patch(color="colorname") to create a colored patch for the legend.
4
Add custom legend and display plot
Use plt.legend() with handles=[blue_patch, green_patch] and labels=["Product A Sales", "Product B Sales"] to add a custom legend. Then call plt.show() to display the plot.
Matplotlib
Hint
Use plt.legend(handles=[...], labels=[...]) to create a custom legend. Then call plt.show() to display the plot.
Practice
(1/5)
1. What is the main purpose of creating custom legend entries in matplotlib?
easy
A. To change the plot background color
B. To increase the plot size
C. To add labels for plot elements that are not automatically labeled
D. To save the plot as an image file
Solution
Step 1: Understand legend purpose
Legends explain what different plot elements represent.
Step 2: Identify custom legend role
Custom legend entries add labels for elements not labeled automatically.
Final Answer:
To add labels for plot elements that are not automatically labeled -> Option C
Quick Check:
Custom legend entries = add labels [OK]
Hint: Custom legends label unlabeled plot parts quickly [OK]
Common Mistakes:
Confusing legend with plot size or color
Thinking legend changes plot background
Assuming legend saves the plot
2. Which of the following is the correct way to create a custom legend entry for a red line using matplotlib.lines.Line2D?
easy
A. Line2D([0], [0], color='red', label='Red Line')
B. Line2D(color='red', label='Red Line')
C. Line2D([0,1], [0,1], color='red')
D. Line2D([0], [0], 'red', label='Red Line')
Solution
Step 1: Check Line2D constructor
Line2D requires x and y data points as first two arguments.
Step 2: Verify correct syntax
Line2D([0], [0], color='red', label='Red Line') uses [0], [0] for points, color='red', and label='Red Line' correctly.
Final Answer:
Line2D([0], [0], color='red', label='Red Line') -> Option A
Quick Check:
Line2D needs x,y points + color + label [OK]
Hint: Line2D needs x and y lists first, then style [OK]
Common Mistakes:
Omitting x and y data points
Passing color as positional argument
Missing label parameter
3. What will be the output legend labels for this code snippet?
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
plt.plot([1, 2, 3], [4, 5, 6], 'b-')
custom_line = Line2D([0], [0], color='red', lw=2)
plt.legend([custom_line], ['Custom Red Line'])
plt.show()
medium
A. A legend with two labels: 'Custom Red Line' and 'blue line'
B. A legend with one label: 'blue line' shown in blue
C. No legend will appear
D. A legend with one label: 'Custom Red Line' shown in red
Solution
Step 1: Analyze plot and legend calls
Plot draws a blue line but legend uses only custom_line handle with label 'Custom Red Line'.
Step 2: Understand legend content
Legend shows only what is passed: one red line with label 'Custom Red Line'.
Final Answer:
A legend with one label: 'Custom Red Line' shown in red -> Option D
Quick Check:
Legend shows passed handles and labels only [OK]
Hint: Legend shows only handles and labels you pass [OK]
Common Mistakes:
Assuming plot lines auto-appear in legend
Expecting multiple legend entries without passing handles
Thinking legend is empty
4. Identify the error in this code that tries to add a custom legend entry for a green square patch:
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
patch = Patch(color='green', label='Green Square')
plt.legend(handles=patch, labels=['Green Square'])
plt.show()
medium
A. Patch cannot be used for legend entries
B. The 'handles' argument should be a list, not a single Patch object
C. The 'label' parameter is missing in Patch
D. plt.show() must come before plt.legend()
Solution
Step 1: Check handles argument type
plt.legend expects handles as a list or iterable, not a single object.
Step 2: Identify fix
Wrap patch in a list: handles=[patch] to fix the error.
Final Answer:
The 'handles' argument should be a list, not a single Patch object -> Option B
Quick Check:
Handles must be list or iterable [OK]
Hint: Always pass handles as a list to plt.legend [OK]
Common Mistakes:
Passing single object instead of list to handles
Ignoring label parameter in Patch
Calling plt.show() before plt.legend()
5. You want to create a legend with a blue dashed line labeled 'Trend' and a red circle marker labeled 'Data Point'. Which code correctly creates custom legend entries for this?