Matplotlib is a powerful Python library for creating visualizations. When working with multiple subplots, however, managing legends can become complex. This article provides efficient methods for creating a single, unified legend across all your subplots.
Table of Contents
- Understanding Subplots in Matplotlib
- Method 1: Using
fig.legend()
- Method 2: Customizing Legend Placement and Appearance
- Method 3: Handling Multiple Lines per Subplot
- Conclusion
- FAQ
Understanding Subplots in Matplotlib
Subplots arrange multiple plots within a single figure. In Matplotlib, you create them using matplotlib.pyplot.subplots()
, which returns a figure object and an array of axes objects (one per subplot).
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2) # 2x2 grid of subplots
# Plot data on each subplot
axes[0, 0].plot([1, 2, 3], [4, 5, 6], label='Line 1')
axes[0, 1].plot([1, 2, 3], [7, 8, 9], label='Line 2')
axes[1, 0].plot([1, 2, 3], [10, 11, 12], label='Line 1')
axes[1, 1].plot([1, 2, 3], [13, 14, 15], label='Line 2')
plt.show()
This creates a 2×2 grid, each with its own legend. We’ll consolidate these into a single legend.
Method 1: Using fig.legend()
The simplest approach uses the figure object’s legend()
method. This requires collecting all legend handles and labels.
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2)
lines1, = axes[0, 0].plot([1, 2, 3], [4, 5, 6], label='Line 1')
lines2, = axes[0, 1].plot([1, 2, 3], [7, 8, 9], label='Line 2')
lines3, = axes[1, 0].plot([1, 2, 3], [10, 11, 12], label='Line 1')
lines4, = axes[1, 1].plot([1, 2, 3], [13, 14, 15], label='Line 2')
# Collect unique handles and labels
handles = [lines1, lines2]
labels = [h.get_label() for h in handles]
fig.legend(handles, labels, loc='upper right')
plt.show()
Note: We only use unique handles to avoid duplicates in the legend. loc
specifies the legend’s position.
Method 2: Customizing Legend Placement and Appearance
You can customize the legend’s location, border, font size, and more.
import matplotlib.pyplot as plt
# ... (plotting code from Method 1) ...
fig.legend(handles, labels, loc='lower center', bbox_to_anchor=(0.5, -0.1), ncol=2, frameon=True, fontsize=12)
plt.show()
Here, we’ve positioned the legend at the bottom center, adjusted vertical position with bbox_to_anchor
, used two columns (ncol=2
), added a border (frameon=True
), and increased font size.
Method 3: Handling Multiple Lines per Subplot
For multiple lines within a subplot, collect all relevant handles and labels.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
line1, = ax.plot([1, 2, 3], [4, 5, 6], label='Line 1')
line2, = ax.plot([1, 2, 3], [7, 8, 9], label='Line 2')
line3, = ax.plot([1, 2, 3], [10, 11, 12], label='Line 3')
fig.legend([line1, line2, line3], [line1.get_label(), line2.get_label(), line3.get_label()], loc='best')
plt.show()
Conclusion
Creating a single legend for all subplots improves the clarity and readability of your Matplotlib visualizations. The methods shown above, using fig.legend()
and proper handle/label management, offer control over legend placement and appearance.
FAQ
- Q: What if I have different line styles? A: The legend will automatically reflect these differences.
- Q: Can I use different colors for the same label? A: Yes, but the legend will only show one color per label. Use distinct labels to differentiate.
- Q: My legend overlaps plots. A: Adjust
bbox_to_anchor
,loc
, font size, or figure size.