0
0
Matplotlibdata~15 mins

Multiple legends in Matplotlib - Deep Dive

Choose your learning style9 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.