Enable Matplotlib’s modern layout engine by passing layout="constrained" to plt.subplots(..., layout="constrained") (or fig = plt.figure(layout="constrained")), which automatically calculates and reserves space for axis titles, tick labels, axis labels, suptitles, and colorbars across all subplots—falling back to fig.tight_layout() for legacy scripts or fig.subplots_adjust(wspace=..., hspace=...) when you need explicit manual padding between subplot rows and columns.
Basic Example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 200)
# 1. Recommended: Enable `layout="constrained"` directly in `plt.subplots()`
fig, axes = plt.subplots(2, 2, figsize=(8, 6), layout="constrained")
fig.suptitle("Sensor Diagnostics (Constrained Layout)", fontsize=14)
for idx, ax in enumerate(axes.flat):
ax.plot(x, np.sin(x + idx))
ax.set_title(f"Channel {idx + 1} Signal")
ax.set_xlabel("Time (seconds)")
ax.set_ylabel("Amplitude (mV)")
# 2. Optional: Fine-tune padding between subplots under constrained layout (`w_pad`, `h_pad`, `wspace`, `hspace`):
fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.08, wspace=0.08)
plt.show()
Key Details & Edge Cases
layout="constrained"supersedestight_layout()(and supportsfig.suptitle()& shared colorbars):fig.tight_layout()ignoresfig.suptitle()by default (causing the main title to overlap top subplot titles unlessrect=[0, 0, 1, 0.95]is passed) and struggles with multi-axes colorbars (fig.colorbar(..., ax=axes)).layout="constrained"accounts for suptitles, external legends, and multi-subplot colorbars automatically and re-runs right before drawing/saving.
- Avoid calling
fig.tight_layout()afterlayout="constrained":- Do not mix both layout engines on the same figure; Matplotlib emits a
UserWarningor replaces the constrained layout engine with the older tight layout engine.
- Do not mix both layout engines on the same figure; Matplotlib emits a
- Reducing clutter on grid subplots with shared axes (
sharex=True, sharey=True):- When a grid of subplots shares the same x- or y-axis scale, pass
sharex=True, sharey=Truetoplt.subplots(...). Matplotlib automatically hides redundant inner tick labels, dramatically freeing vertical and horizontal breathing room between subplots.
- When a grid of subplots shares the same x- or y-axis scale, pass
- Manual spacing overrides with
fig.subplots_adjust()(when layout engines are disabled):- If you need exact fractional spacing without automatic resizing, leave
layout=Noneand callfig.subplots_adjust(left=0.1, right=0.95, bottom=0.1, top=0.9, wspace=0.3, hspace=0.4)—wherewspaceandhspaceare expressed as fractions of the average subplot width and height.
- If you need exact fractional spacing without automatic resizing, leave
- Preventing clipped outer labels when exporting (
bbox_inches="tight"):- Even with good internal subplot spacing, rotated x-tick labels or outer legends can still clip at the figure border during export. Pass
fig.savefig("plot.png", dpi=300, bbox_inches="tight")when saving to disk.
- Even with good internal subplot spacing, rotated x-tick labels or outer legends can still clip at the figure border during export. Pass
- Global default via
rcParams:- To enable constrained layout automatically across every figure in a script or notebook without passing
layout="constrained"each time, setplt.rcParams["figure.constrained_layout.use"] = Trueat the top of your script.
- To enable constrained layout automatically across every figure in a script or notebook without passing
Comparison of Subplot Spacing & Overlap-Prevention Methods in Matplotlib
| Method | Handles fig.suptitle() & Multi-Axes Colorbars? |
Dynamically Adjusts on Resizing / Label Edits? | Manual Fine-Tuning Control | Best Used When |
|---|---|---|---|---|
plt.subplots(..., layout="constrained") (Recommended) |
Yes (handles suptitles, colorbars, and legends natively) | Yes (runs automatically at draw/save time) | fig.get_layout_engine().set(w_pad=..., h_pad=..., wspace=..., hspace=...) |
All modern Matplotlib (3.6+) multi-panel figures, grids, and dashboards. |
fig.tight_layout(pad=1.08, h_pad=..., w_pad=...) |
Partial (suptitle overlaps unless rect= is tuned) |
No (one-shot static calculation when called) | pad, h_pad, w_pad, rect=[left, bottom, right, top] |
Legacy scripts or quick single-pass fixes on simple subplot grids. |
fig.subplots_adjust(wspace=..., hspace=...) |
No (manual margin calculation required) | No (fixed fractional margins) | Exact left, right, top, bottom, wspace, hspace |
Custom layouts requiring exact, reproducible margin coordinates across multiple exported figures. |
sharex=True, sharey=True (paired with layout="constrained") |
Yes | Yes | Removes redundant inner tick labels automatically | Multi-panel grids comparing plots over identical x- or y-axis ranges. |
You must log in or register to comment.
