Adjust Spacing Between Subplots in Matplotlib Easily
To adjust spacing between subplots in
matplotlib, use plt.tight_layout() for automatic spacing or plt.subplots_adjust() to manually set spacing parameters like left, right, top, bottom, wspace, and hspace. These control the space around and between subplots.Syntax
The main ways to adjust subplot spacing are:
plt.tight_layout(): Automatically adjusts subplot params for a clean layout.plt.subplots_adjust(left=None, right=None, top=None, bottom=None, wspace=None, hspace=None): Manually sets spacing.
Parameters explained:
left, right, top, bottom: Float values (0 to 1) controlling the edges of the subplots area.wspace: Width space between subplots as a fraction of average subplot width.hspace: Height space between subplots as a fraction of average subplot height.
python
plt.tight_layout() plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1, wspace=0.4, hspace=0.4)
Example
This example creates a 2x2 grid of subplots and adjusts the spacing between them using subplots_adjust. It shows how changing wspace and hspace affects the gaps.
python
import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 2) for i in range(2): for j in range(2): axs[i, j].text(0.5, 0.5, f'Subplot {i},{j}', ha='center', va='center') axs[i, j].set_xticks([]) axs[i, j].set_yticks([]) plt.subplots_adjust(wspace=0.5, hspace=0.7) plt.show()
Output
A 2x2 grid of subplots with visible spacing between them, wider horizontally and vertically.
Common Pitfalls
Common mistakes when adjusting subplot spacing include:
- Not calling
plt.tight_layout()orplt.subplots_adjust()after creating subplots, so spacing stays default and cramped. - Setting
wspaceorhspacetoo small, causing overlapping labels or titles. - Using
tight_layoutandsubplots_adjusttogether without care, which can conflict.
python
import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 2) for ax in axs.flat: ax.set_title('Title') # Wrong: no spacing adjustment, titles overlap plt.show() # Right: use tight_layout to fix spacing plt.tight_layout() plt.show()
Output
First plot shows overlapping titles; second plot shows titles spaced nicely.
Quick Reference
Summary tips for adjusting subplot spacing:
- Use
plt.tight_layout()for quick automatic spacing. - Use
plt.subplots_adjust()to fine-tune margins and gaps. wspacecontrols horizontal gap;hspacecontrols vertical gap.- Margins (
left,right,top,bottom) control subplot area edges.
Key Takeaways
Use plt.tight_layout() for automatic and simple subplot spacing adjustment.
Use plt.subplots_adjust() to manually control spacing with parameters like wspace and hspace.
Avoid overlapping labels by increasing wspace and hspace values if needed.
Call spacing adjustment functions after creating all subplots.
Do not mix tight_layout and subplots_adjust carelessly to prevent conflicts.