Adjusting Subplot Spacing and Layout
What You'll Learn
You'll learn how to control the spacing between subplots to create professional, readable visualizations without overlapping elements.
The Problem: Cramped Subplots
When you create multiple subplots, Matplotlib's default spacing often causes titles, labels, and tick marks to overlap or get cut off. It's like arranging furniture in a room—you need proper spacing between pieces so everything is accessible and looks clean.
Three Solutions for Better Layout
tight_layout()
The simplest fix—Matplotlib automatically adjusts spacing to prevent overlap:
fig, axes = plt.subplots(2, 2)
# ... add your plots ...
plt.tight_layout()
plt.show()
Think of this as an "auto-arrange" button. It works well for most standard cases.
subplots_adjust()
For manual control, specify exact spacing parameters:
fig, axes = plt.subplots(2, 2)
# ... add your plots ...
plt.subplots_adjust(left=0.1, right=0.95, top=0.9, bottom=0.1,
hspace=0.4, wspace=0.3)
plt.show()
left,right,top,bottom: margins around the entire figure (0 to 1)hspace: vertical space between rows (height space)wspace: horizontal space between columns (width space)
constrained_layout
The modern approach—enable at figure creation for dynamic adjustment:
fig, axes = plt.subplots(2, 2, constrained_layout=True)
# ... add your plots ...
plt.show()
This is like tight_layout() but handles more complex scenarios, including colorbars and nested subplots.
When to Use Which?
- Quick fix: Use
tight_layout() - Precise control: Use
subplots_adjust() - Complex layouts: Use
constrained_layout=True
Key Takeaway: Control subplot spacing with tight_layout() for automatic adjustment, subplots_adjust() for manual fine-tuning, or constrained_layout=True for advanced scenarios—ensuring your multi-panel visualizations look polished and professional.