Multiple legends in Matplotlib - Time & Space Complexity
When creating multiple legends in matplotlib, the program does extra work to draw each legend separately.
We want to know how the time to draw grows as we add more legends.
Analyze the time complexity of this matplotlib code snippet.
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')
legend1 = ax.legend(handles=[line1], loc='upper left')
ax.add_artist(legend1)
legend2 = ax.legend(handles=[line2], loc='upper right')
ax.add_artist(legend2)
plt.show()
This code creates a plot with two lines and adds two separate legends for each line.
Look for repeated actions that take time.
- Primary operation: Drawing each legend box and its items.
- How many times: Once per legend added (here, twice).
Adding more legends means more boxes and labels to draw.
| Number of Legends (n) | Approx. Drawing Steps |
|---|---|
| 1 | 1 unit (one legend drawn) |
| 5 | 5 units (five legends drawn) |
| 10 | 10 units (ten legends drawn) |
Pattern observation: The drawing work grows directly with the number of legends added.
Time Complexity: O(n)
This means the time to draw legends grows in a straight line as you add more legends.
[X] Wrong: "Adding multiple legends is just as fast as one legend because they are small."
[OK] Correct: Each legend requires separate drawing steps, so more legends mean more work and more time.
Understanding how adding multiple legends affects drawing time helps you think about performance when making complex plots.
What if we combined all labels into a single legend instead of multiple legends? How would the time complexity change?
Practice
matplotlib plot?Solution
Step 1: Understand the purpose of legends
Legends help identify what each line or marker in a plot represents.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.Final Answer:
To label different groups or data sets separately on the same plot -> Option CQuick Check:
Multiple legends = separate group labels [OK]
- Thinking legends change plot colors
- Confusing legends with saving files
- Assuming legends resize plots
matplotlib method is used to keep the first legend visible when adding a second legend?Solution
Step 1: Identify how legends are added
Legends are usually added withplt.legend()orax.legend().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 usingax.add_artist().Final Answer:
ax.add_artist() -> Option AQuick Check:
Keep first legend visible = add_artist() [OK]
- Using plt.legend() twice without add_artist()
- Calling plt.show() to fix legends
- Trying to set title to fix legends
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()
Solution
Step 1: Analyze legend creation
The first legend is created for 'Line 1' and added as an artist to keep it visible.Step 2: Analyze second legend addition
The second legend is created for 'Line 2' and placed at upper right. Both legends appear separately.Final Answer:
Two legends: 'Line 1' at upper left and 'Line 2' at upper right -> Option AQuick Check:
add_artist() + second legend = two legends [OK]
- Expecting only one legend to show
- Forgetting to add_artist() for first legend
- Placing both legends at same location
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()
Solution
Step 1: Understand legend behavior
Callingax.legend()twice replaces the previous legend each time.Step 2: Identify why only one legend appears
Without usingax.add_artist(), the first legend is removed when the second is added.Final Answer:
Second legend call overwrites the first, so only one legend shows -> Option BQuick Check:
Multiple legend calls overwrite without add_artist() [OK]
- Assuming multiple legend() calls stack automatically
- Thinking missing plt.show() causes no plot
- Believing labels cause syntax errors
Solution
Step 1: Understand legend placement
Legends placed at differentlocpositions avoid overlap visually.Step 2: Use add_artist() to keep multiple legends
Adding the first legend as an artist keeps it visible when adding others.Step 3: Create all three legends with distinct locations
Creating legends separately withlocset to 'upper left', 'upper right', and 'lower left' places them without overlap.Final Answer:
Create first legend, add it with ax.add_artist(), then create second and third legends with different loc values -> Option DQuick Check:
add_artist() + distinct loc = multiple legends no overlap [OK]
- Calling legend() multiple times without add_artist()
- Placing all legends at same location causing overlap
- Using single legend for all groups losing clarity
Ready to prove it?
Pass the test and this pattern moves unknown
