Sometimes you want to explain different groups of lines or points separately in one plot. Multiple legends help you do that clearly.
Multiple legends in Matplotlib
legend1 = plt.legend(handles=group1_handles, loc='upper left') plt.gca().add_artist(legend1) plt.legend(handles=group2_handles, loc='upper right')
You create the first legend and add it to the plot as an artist.
Then you create the second legend normally. This way both show up.
import matplotlib.pyplot as plt line1, = plt.plot([1, 2, 3], label='Group A') line2, = plt.plot([3, 2, 1], label='Group B') legend1 = plt.legend(handles=[line1], loc='upper left') plt.gca().add_artist(legend1) plt.legend(handles=[line2], loc='upper right') plt.show()
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) line1, = plt.plot(x, np.sin(x), 'r-', label='Sine wave') line2, = plt.plot(x, np.cos(x), 'b--', label='Cosine wave') scatter = plt.scatter([2, 4, 6], [0, 0, 0], c='g', label='Points') legend1 = plt.legend(handles=[line1, line2], title='Lines', loc='upper left') plt.gca().add_artist(legend1) plt.legend(handles=[scatter], title='Markers', loc='lower right') plt.show()
This program plots two decay curves and some sample points. It adds two legends: one for the lines and one for the points, placed in different corners for clarity.
import matplotlib.pyplot as plt import numpy as np # Create data x = np.linspace(0, 5, 100) y1 = np.exp(-x) y2 = np.exp(-0.5 * x) # Plot two lines line1, = plt.plot(x, y1, 'b-', label='Fast decay') line2, = plt.plot(x, y2, 'r--', label='Slow decay') # Plot some points points = plt.scatter([1, 2, 3], [0.8, 0.6, 0.4], c='green', label='Samples') # First legend for lines legend1 = plt.legend(handles=[line1, line2], title='Decay types', loc='upper right') plt.gca().add_artist(legend1) # Second legend for points plt.legend(handles=[points], title='Data points', loc='lower left') plt.xlabel('Time') plt.ylabel('Value') plt.title('Multiple Legends Example') plt.show()
Always add the first legend as an artist before adding the second one.
Use different locations to avoid legends overlapping.
You can customize legend titles and styles for better clarity.
Multiple legends help explain different data groups clearly in one plot.
Create the first legend and add it as an artist, then add the second normally.
Place legends in different locations to keep the plot readable.
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
