Bird
Raised Fist0
Matplotlibdata~15 mins

Multiple legends in Matplotlib - Deep Dive

Choose your learning style10 modes available
Overview - Multiple legends
What is it?
Multiple legends in matplotlib allow you to add more than one legend box to a single plot. Each legend can describe different groups of data or different plot elements. This helps make complex plots easier to understand by clearly separating information. Without multiple legends, all plot descriptions would be crowded into one box, making it confusing.
Why it matters
When you have many types of data or styles in one plot, a single legend can become cluttered and unclear. Multiple legends let you organize explanations logically, improving readability and communication. Without this, viewers might misinterpret the data or miss important details, reducing the plot's usefulness.
Where it fits
Before learning multiple legends, you should know how to create basic plots and add a single legend in matplotlib. After mastering multiple legends, you can explore advanced plot customization, interactive plotting, and dashboard creation.
Mental Model
Core Idea
Multiple legends let you add separate explanation boxes to a plot, each describing different parts clearly and independently.
Think of it like...
Imagine a map with different colored routes for buses, trains, and bikes. Instead of one big confusing key, you have separate keys for each transport type, making it easier to understand each route.
┌─────────────────────────────┐
│          Plot Area          │
│  ┌───────────────┐          │
│  │ Legend 1:     │          │
│  │ - Red line   ├─────────┐│
│  │ - Blue dots  │         ││
│  └───────────────┘         ││
│                           ││
│  ┌───────────────┐         ││
│  │ Legend 2:     │         ││
│  │ - Green bars │         ││
│  └───────────────┘         ││
└─────────────────────────────┘│
                               │
Separate legends explain different plot elements clearly.
Build-Up - 7 Steps
1
FoundationBasic plot with single legend
🤔
Concept: How to create a simple plot and add one legend describing all elements.
import matplotlib.pyplot as plt x = [1, 2, 3] y1 = [2, 3, 4] y2 = [4, 3, 2] plt.plot(x, y1, label='Line 1') plt.plot(x, y2, label='Line 2') plt.legend() plt.show()
Result
A plot with two lines and one legend box showing 'Line 1' and 'Line 2'.
Understanding how to add a single legend is the foundation for managing plot explanations.
2
FoundationLimitations of single legend
🤔
Concept: Why one legend can be confusing when many plot elements exist.
Imagine adding bars and scatter points with different meanings but putting all labels in one legend. It becomes crowded and hard to read.
Result
A single legend box with many entries that overlap or confuse viewers.
Recognizing the limits of one legend motivates learning multiple legends for clarity.
3
IntermediateCreating multiple legends manually
🤔Before reading on: do you think matplotlib supports multiple legends directly or requires a workaround? Commit to your answer.
Concept: Matplotlib does not support multiple legends by default, but you can add extra legends manually using artist handles.
import matplotlib.pyplot as plt x = [1, 2, 3] y1 = [2, 3, 4] y2 = [4, 3, 2] y3 = [1, 4, 2] line1, = plt.plot(x, y1, 'r-', label='Red Line') line2, = plt.plot(x, y2, 'b-', label='Blue Line') scatter = plt.scatter(x, y3, color='green', label='Green Points') # First legend for lines leg1 = plt.legend(handles=[line1, line2], loc='upper left') plt.gca().add_artist(leg1) # Add first legend manually # Second legend for scatter plt.legend(handles=[scatter], loc='lower right') plt.show()
Result
A plot with two separate legend boxes: one for lines and one for scatter points.
Knowing how to add legends manually lets you organize plot explanations flexibly.
4
IntermediateUsing legend handles and labels
🤔Before reading on: do you think legend handles must be plot objects or can be any artist? Commit to your answer.
Concept: Legends use handles (plot elements) and labels to create entries; you can select which handles to include in each legend.
import matplotlib.pyplot as plt x = [1, 2, 3] y1 = [2, 3, 4] y2 = [4, 3, 2] line1, = plt.plot(x, y1, 'r-', label='Red Line') line2, = plt.plot(x, y2, 'b-', label='Blue Line') # Create legend with only one line plt.legend(handles=[line1], loc='upper left') plt.show()
Result
A plot with only one legend entry for the red line.
Selecting specific handles controls what each legend explains, enabling multiple legends.
5
AdvancedPositioning multiple legends precisely
🤔Before reading on: do you think legend positions can overlap if not managed? Commit to your answer.
Concept: You can control legend positions with loc and bbox_to_anchor to avoid overlap and improve layout.
import matplotlib.pyplot as plt x = [1, 2, 3] y1 = [2, 3, 4] y2 = [4, 3, 2] y3 = [1, 4, 2] line1, = plt.plot(x, y1, 'r-', label='Red Line') line2, = plt.plot(x, y2, 'b-', label='Blue Line') scatter = plt.scatter(x, y3, color='green', label='Green Points') leg1 = plt.legend(handles=[line1, line2], loc='upper left', bbox_to_anchor=(0, 1)) plt.gca().add_artist(leg1) plt.legend(handles=[scatter], loc='upper left', bbox_to_anchor=(0, 0.9)) plt.show()
Result
Two legends stacked vertically without overlapping, improving readability.
Precise control of legend placement prevents clutter and confusion in complex plots.
6
AdvancedCustomizing legend appearance separately
🤔
Concept: Each legend can have its own style, font size, frame, and transparency for better visual distinction.
import matplotlib.pyplot as plt x = [1, 2, 3] y1 = [2, 3, 4] y2 = [4, 3, 2] line1, = plt.plot(x, y1, 'r-', label='Red Line') line2, = plt.plot(x, y2, 'b-', label='Blue Line') leg1 = plt.legend(handles=[line1], loc='upper left', fontsize='small', frameon=False) plt.gca().add_artist(leg1) plt.legend(handles=[line2], loc='upper right', fontsize='large', framealpha=0.5) plt.show()
Result
Two legends with different font sizes and frame styles, making each distinct.
Customizing legends individually enhances clarity and visual appeal.
7
ExpertAutomating multiple legends with custom functions
🤔Before reading on: do you think automating legend creation can reduce errors in complex plots? Commit to your answer.
Concept: You can write functions to generate multiple legends automatically based on plot groups, improving efficiency and consistency.
import matplotlib.pyplot as plt def add_multiple_legends(ax, groups): for i, (handles, loc, bbox) in enumerate(groups): leg = ax.legend(handles=handles, loc=loc, bbox_to_anchor=bbox) ax.add_artist(leg) x = [1, 2, 3] y1 = [2, 3, 4] y2 = [4, 3, 2] y3 = [1, 4, 2] fig, ax = plt.subplots() line1, = ax.plot(x, y1, 'r-', label='Red Line') line2, = ax.plot(x, y2, 'b-', label='Blue Line') scatter = ax.scatter(x, y3, color='green', label='Green Points') groups = [ ([line1, line2], 'upper left', (0, 1)), ([scatter], 'upper left', (0, 0.9)) ] add_multiple_legends(ax, groups) plt.show()
Result
Plot with multiple legends added cleanly by a reusable function.
Automating legend creation reduces repetitive code and errors in complex visualizations.
Under the Hood
Matplotlib creates legends as separate artist objects that can be added to the plot's axes. By default, only one legend is shown because calling plt.legend() replaces the previous one. To have multiple legends, you must add each legend artist manually to the axes using add_artist(). Each legend artist manages its own handles, labels, and position independently.
Why designed this way?
Matplotlib was designed to keep the API simple for common cases with one legend. Supporting multiple legends directly would complicate the interface and layout logic. Instead, it provides low-level control to add multiple legend artists manually, giving flexibility to advanced users without burdening beginners.
┌─────────────────────────────┐
│          Axes Object        │
│  ┌───────────────────────┐│
│  │ Legend Artist 1       ││
│  │ - Handles, Labels     ││
│  │ - Position, Style     ││
│  └───────────────────────┘│
│  ┌───────────────────────┐│
│  │ Legend Artist 2       ││
│  │ - Handles, Labels     ││
│  │ - Position, Style     ││
│  └───────────────────────┘│
└─────────────────────────────┘
Each legend is an independent artist added to the axes.
Myth Busters - 4 Common Misconceptions
Quick: Does calling plt.legend() twice add two legends automatically? Commit yes or no.
Common Belief:Calling plt.legend() multiple times will add multiple legends to the plot automatically.
Tap to reveal reality
Reality:Each call to plt.legend() replaces the previous legend unless you manually add the first legend artist back with add_artist().
Why it matters:Without this knowledge, learners get confused when only one legend appears despite multiple calls, leading to frustration and wasted time.
Quick: Can you create multiple legends by passing multiple labels in one plt.legend() call? Commit yes or no.
Common Belief:You can create multiple legends by listing all labels in one legend call.
Tap to reveal reality
Reality:One legend can only create one box; to have multiple boxes, you must create multiple legend artists separately.
Why it matters:Trying to cram all labels into one legend reduces clarity and defeats the purpose of multiple legends.
Quick: Do legend handles have to be plot lines only? Commit yes or no.
Common Belief:Legend handles must be line plots or similar; scatter or bar plots cannot be used as handles.
Tap to reveal reality
Reality:Any plot element (lines, scatter, bars) can be a legend handle as long as it is an artist object.
Why it matters:Misunderstanding this limits the ability to create accurate legends for diverse plot types.
Quick: Is it safe to place multiple legends anywhere without overlap? Commit yes or no.
Common Belief:Matplotlib automatically manages legend placement to avoid overlap when multiple legends exist.
Tap to reveal reality
Reality:Matplotlib does not manage multiple legend placement automatically; you must manually position them to avoid overlap.
Why it matters:Ignoring this causes legends to overlap, making plots unreadable and unprofessional.
Expert Zone
1
Adding multiple legends requires careful management of the plot's artist stack to avoid one legend hiding another.
2
Legend artists can be customized independently, including font properties, frame visibility, and transparency, allowing nuanced visual storytelling.
3
Automating legend creation with functions or classes improves maintainability in complex plotting scripts or dashboards.
When NOT to use
Multiple legends are not suitable when the plot is simple or when a single concise legend suffices. In such cases, use a single legend with clear grouping or annotations. For interactive plots, consider tooltips or dynamic legends instead.
Production Patterns
Professionals use multiple legends to separate categories like data types, experimental conditions, or statistical summaries. In dashboards, multiple legends improve user comprehension by grouping related plot elements logically.
Connections
Layered architecture in software design
Both use separate layers/components to organize complex information clearly.
Understanding how multiple legends act as independent layers helps grasp modular design principles in software.
User interface design
Multiple legends are like separate UI panels that organize controls or information logically.
Knowing this connection highlights the importance of clear, separated information areas for user comprehension.
Cartography (map making)
Multiple legends correspond to different map keys for various features like roads, rivers, and landmarks.
Recognizing this link shows how visualization principles apply across fields to improve clarity.
Common Pitfalls
#1Only calling plt.legend() multiple times without adding previous legends manually.
Wrong approach:plt.plot(x, y1, label='Line 1') plt.plot(x, y2, label='Line 2') plt.legend(loc='upper left') plt.legend(loc='lower right') plt.show()
Correct approach:line1, = plt.plot(x, y1, label='Line 1') line2, = plt.plot(x, y2, label='Line 2') leg1 = plt.legend(handles=[line1], loc='upper left') plt.gca().add_artist(leg1) plt.legend(handles=[line2], loc='lower right') plt.show()
Root cause:Misunderstanding that plt.legend() replaces the previous legend instead of adding a new one.
#2Passing all plot elements to one legend when multiple legends are needed.
Wrong approach:plt.legend(handles=[line1, line2, scatter], loc='best')
Correct approach:leg1 = plt.legend(handles=[line1, line2], loc='upper left') plt.gca().add_artist(leg1) plt.legend(handles=[scatter], loc='lower right')
Root cause:Not realizing that one legend box cannot separate different groups clearly.
#3Not controlling legend positions, causing overlap.
Wrong approach:leg1 = plt.legend(handles=[line1], loc='upper left') plt.gca().add_artist(leg1) plt.legend(handles=[line2], loc='upper left')
Correct approach:leg1 = plt.legend(handles=[line1], loc='upper left', bbox_to_anchor=(0, 1)) plt.gca().add_artist(leg1) plt.legend(handles=[line2], loc='upper left', bbox_to_anchor=(0, 0.9))
Root cause:Assuming matplotlib automatically arranges multiple legends without overlap.
Key Takeaways
Multiple legends let you add separate explanation boxes to a plot, improving clarity when many elements exist.
Matplotlib does not support multiple legends automatically; you must add each legend artist manually with add_artist().
Legend handles can be any plot element, and selecting which handles go into each legend controls what is explained.
Precise positioning and styling of each legend prevent overlap and improve visual distinction.
Automating multiple legend creation with functions enhances code maintainability in complex plots.

Practice

(1/5)
1. What is the main reason to use multiple legends in a matplotlib plot?
easy
A. To increase the plot size automatically
B. To change the color of the plot lines
C. To label different groups or data sets separately on the same plot
D. To save the plot as an image file

Solution

  1. Step 1: Understand the purpose of legends

    Legends help identify what each line or marker in a plot represents.
  2. Step 2: Recognize why multiple legends are needed

    When a plot has multiple groups or categories, separate legends make it easier to understand each group distinctly.
  3. Final Answer:

    To label different groups or data sets separately on the same plot -> Option C
  4. Quick Check:

    Multiple legends = separate group labels [OK]
Hint: Multiple legends label different groups clearly [OK]
Common Mistakes:
  • Thinking legends change plot colors
  • Confusing legends with saving files
  • Assuming legends resize plots
2. Which matplotlib method is used to keep the first legend visible when adding a second legend?
easy
A. ax.add_artist()
B. plt.show()
C. plt.legend()
D. ax.set_title()

Solution

  1. Step 1: Identify how legends are added

    Legends are usually added with plt.legend() or ax.legend().
  2. Step 2: Understand how to keep multiple legends

    To keep the first legend visible after adding a second, you must add the first legend as an artist using ax.add_artist().
  3. Final Answer:

    ax.add_artist() -> Option A
  4. Quick Check:

    Keep first legend visible = add_artist() [OK]
Hint: Use add_artist() to keep first legend visible [OK]
Common Mistakes:
  • Using plt.legend() twice without add_artist()
  • Calling plt.show() to fix legends
  • Trying to set title to fix legends
3. What will the following code display?
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
line1, = ax.plot([1, 2, 3], label='Line 1')
line2, = ax.plot([3, 2, 1], label='Line 2')
leg1 = ax.legend(handles=[line1], loc='upper left')
ax.add_artist(leg1)
ax.legend(handles=[line2], loc='upper right')
plt.show()
medium
A. Two legends: 'Line 1' at upper left and 'Line 2' at upper right
B. Only one legend showing 'Line 2' at upper right
C. Only one legend showing 'Line 1' at upper left
D. No legends displayed

Solution

  1. Step 1: Analyze legend creation

    The first legend is created for 'Line 1' and added as an artist to keep it visible.
  2. Step 2: Analyze second legend addition

    The second legend is created for 'Line 2' and placed at upper right. Both legends appear separately.
  3. Final Answer:

    Two legends: 'Line 1' at upper left and 'Line 2' at upper right -> Option A
  4. Quick Check:

    add_artist() + second legend = two legends [OK]
Hint: add_artist() keeps first legend when adding second [OK]
Common Mistakes:
  • Expecting only one legend to show
  • Forgetting to add_artist() for first legend
  • Placing both legends at same location
4. Identify the error in this code that tries to add two legends:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
line1, = ax.plot([1, 2, 3], label='A')
line2, = ax.plot([3, 2, 1], label='B')
ax.legend(handles=[line1], loc='upper left')
ax.legend(handles=[line2], loc='upper right')
plt.show()
medium
A. Syntax error due to missing parentheses
B. Second legend call overwrites the first, so only one legend shows
C. Plot lines are not labeled correctly
D. The plot will not display because plt.show() is missing

Solution

  1. Step 1: Understand legend behavior

    Calling ax.legend() twice replaces the previous legend each time.
  2. Step 2: Identify why only one legend appears

    Without using ax.add_artist(), the first legend is removed when the second is added.
  3. Final Answer:

    Second legend call overwrites the first, so only one legend shows -> Option B
  4. Quick Check:

    Multiple legend calls overwrite without add_artist() [OK]
Hint: Use add_artist() to keep multiple legends visible [OK]
Common Mistakes:
  • Assuming multiple legend() calls stack automatically
  • Thinking missing plt.show() causes no plot
  • Believing labels cause syntax errors
5. You want to plot three data groups with separate legends placed at 'upper left', 'upper right', and 'lower left' without overlap. Which approach correctly achieves this?
hard
A. Plot all lines without legends and add a single legend manually
B. Call ax.legend() three times without add_artist(), changing loc each time
C. Use plt.legend() once with all labels combined
D. Create first legend, add it with ax.add_artist(), then create second and third legends with different loc values

Solution

  1. Step 1: Understand legend placement

    Legends placed at different loc positions avoid overlap visually.
  2. Step 2: Use add_artist() to keep multiple legends

    Adding the first legend as an artist keeps it visible when adding others.
  3. Step 3: Create all three legends with distinct locations

    Creating legends separately with loc set to 'upper left', 'upper right', and 'lower left' places them without overlap.
  4. Final Answer:

    Create first legend, add it with ax.add_artist(), then create second and third legends with different loc values -> Option D
  5. Quick Check:

    add_artist() + distinct loc = multiple legends no overlap [OK]
Hint: Add first legend as artist, set loc differently for others [OK]
Common Mistakes:
  • Calling legend() multiple times without add_artist()
  • Placing all legends at same location causing overlap
  • Using single legend for all groups losing clarity
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