Bird
Raised Fist0
Matplotlibdata~10 mins

Custom legend entries in Matplotlib - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Custom legend entries
Create plot elements
↓
Define custom legend handles
↓
Call legend() with custom handles and labels
↓
Display plot with custom legend
First, create plot elements. Then define custom legend handles. Next, call legend() with these handles and labels. Finally, show the plot with the custom legend.
Execution Sample
Matplotlib
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

plt.plot([1,2,3], label='Line 1')
custom_handle = Line2D([0], [0], color='red', lw=2)
plt.legend(handles=[custom_handle], labels=['Custom Red Line'])
plt.show()
This code plots a line but shows a custom legend entry with a red line instead of the default.
Execution Table
StepActionPlot ElementsLegend HandlesLegend LabelsResult
1Import matplotlib and Line2DNo plot yetNoneNoneReady to plot
2Plot line with label 'Line 1'Line plotted (default blue)NoneNoneLine visible on plot
3Create custom Line2D handle (red line)Line plottedRed line handle createdNoneCustom handle ready
4Call plt.legend() with custom handle and labelLine plottedRed line handle['Custom Red Line']Legend shows red line with label
5Show plotLine plottedRed line handle['Custom Red Line']Plot displayed with custom legend
💡 Plot displayed with custom legend replacing default legend entries
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
pltmatplotlib.pyplot moduleplot createdplot createdplot createdplot displayed
custom_handleundefinedundefinedLine2D object (red line)Line2D object (red line)Line2D object (red line)
legend handlesNoneNoneNone[custom_handle][custom_handle]
legend labelsNoneNoneNone['Custom Red Line']['Custom Red Line']
Key Moments - 3 Insights
Why does the legend show the custom red line instead of the plotted blue line?
Because in step 4, plt.legend() is called with the custom handle and label, overriding the default legend entries from the plot (see execution_table row 4).
Can we add multiple custom legend entries not linked to plotted data?
Yes, by creating multiple custom handles and passing them all in the handles list with corresponding labels in plt.legend(), as shown in step 4.
What happens if we call plt.legend() without handles or labels?
Matplotlib automatically uses the labels from plotted elements. Custom handles override this behavior (see step 4 vs step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 3, what is the state of 'custom_handle'?
AIt is undefined
BIt is a Line2D object representing a red line
CIt is the plotted blue line
DIt is a legend label string
💡 Hint
Check the 'custom_handle' column in variable_tracker after step 3
At which step does the legend start showing the custom red line instead of the default plot line?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look at the 'Legend Handles' and 'Result' columns in execution_table
If we remove the 'handles' argument in plt.legend(), what will the legend show?
ANo legend will appear
BThe custom red line legend entry
CThe default legend from plotted lines
DAn error will occur
💡 Hint
Refer to key_moments about default legend behavior when no handles are passed
Concept Snapshot
Custom legend entries in matplotlib:
- Create plot elements normally
- Define custom legend handles (e.g., Line2D objects)
- Call plt.legend(handles=[...], labels=[...]) to override default legend
- Useful to show legend entries not directly linked to plotted data
- plt.show() displays the plot with custom legend
Full Transcript
This visual execution shows how to create custom legend entries in matplotlib. First, we import matplotlib and plot a line. Then, we create a custom legend handle using Line2D with a red color. Next, we call plt.legend() passing this custom handle and a label, which replaces the default legend entry. Finally, we display the plot with the custom legend. The variable tracker shows how the custom handle and legend labels are set step-by-step. Key moments clarify why the custom legend overrides the default and how to add multiple custom entries. The quiz tests understanding of when and how the custom legend appears.

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

  1. Step 1: Understand legend purpose

    Legends explain what different plot elements represent.
  2. Step 2: Identify custom legend role

    Custom legend entries add labels for elements not labeled automatically.
  3. Final Answer:

    To add labels for plot elements that are not automatically labeled -> Option C
  4. 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

  1. Step 1: Check Line2D constructor

    Line2D requires x and y data points as first two arguments.
  2. 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.
  3. Final Answer:

    Line2D([0], [0], color='red', label='Red Line') -> Option A
  4. 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

  1. Step 1: Analyze plot and legend calls

    Plot draws a blue line but legend uses only custom_line handle with label 'Custom Red Line'.
  2. Step 2: Understand legend content

    Legend shows only what is passed: one red line with label 'Custom Red Line'.
  3. Final Answer:

    A legend with one label: 'Custom Red Line' shown in red -> Option D
  4. 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

  1. Step 1: Check handles argument type

    plt.legend expects handles as a list or iterable, not a single object.
  2. Step 2: Identify fix

    Wrap patch in a list: handles=[patch] to fix the error.
  3. Final Answer:

    The 'handles' argument should be a list, not a single Patch object -> Option B
  4. 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?
hard
A. from matplotlib.lines import Line2D legend_elements = [Line2D([0], [0], color='blue', lw=2, linestyle='--', label='Trend'), Line2D([0], [0], marker='o', color='red', linestyle='', label='Data Point')] plt.legend(handles=legend_elements)
B. from matplotlib.patches import Patch legend_elements = [Patch(color='blue', label='Trend'), Patch(color='red', label='Data Point')] plt.legend(handles=legend_elements)
C. plt.legend(['Trend', 'Data Point'], loc='best')
D. plt.legend(['blue dashed line', 'red circle'])

Solution

  1. Step 1: Identify correct legend handles

    Blue dashed line and red circle marker require Line2D objects with correct styles.
  2. Step 2: Verify code correctness

    from matplotlib.lines import Line2D legend_elements = [Line2D([0], [0], color='blue', lw=2, linestyle='--', label='Trend'), Line2D([0], [0], marker='o', color='red', linestyle='', label='Data Point')] plt.legend(handles=legend_elements) creates Line2D with color='blue', linestyle='--' for 'Trend' and marker='o', color='red' for 'Data Point', then passes handles to plt.legend.
  3. Final Answer:

    from matplotlib.lines import Line2D legend_elements = [Line2D([0], [0], color='blue', lw=2, linestyle='--', label='Trend'), Line2D([0], [0], marker='o', color='red', linestyle='', label='Data Point')] plt.legend(handles=legend_elements) -> Option A
  4. Quick Check:

    Use Line2D with style and marker for custom legend [OK]
Hint: Use Line2D with marker and linestyle for custom legend [OK]
Common Mistakes:
  • Using Patch for line and marker legend
  • Passing only label strings without handles
  • Ignoring linestyle or marker parameters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard