Complex Layouts
Real figures are rarely a perfectly regular grid. A dashboard might have one wide chart on top and two small ones underneath, or a scatter plot with histograms along its edges. Matplotlib offers three tools for this: layout engines, subplot_mosaic and GridSpec.
Layout engines: tight and constrained
When panels crowd each other, labels overlap. You have already met fig.tight_layout(). The newer constrained layout does the same job automatically every time the figure is drawn, and it also handles colorbars and figure titles well. Turn it on when creating the figure:
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2, figsize=(7, 5), layout="constrained")
x = np.linspace(0, 1, 50)
for i, ax in enumerate(axes.flat):
ax.plot(x, x ** (i + 1))
ax.set_title(f"Power {i + 1}")
ax.set_xlabel("input value")
ax.set_ylabel("output value")
fig.suptitle("Constrained layout keeps labels apart")
plt.show()
print("Layout engine:", type(fig.get_layout_engine()).__name__)Layout engine: ConstrainedLayoutEngine
Tip: Use either
layout="constrained"ortight_layout(), not both. Constrained layout is the recommended default for new code.
subplot_mosaic: draw the layout as text
plt.subplot_mosaic() lets you describe a layout with a list of rows, where each name is one Axes. A name repeated across cells makes that Axes span them. It returns a dictionary of Axes keyed by name:
import numpy as np
import matplotlib.pyplot as plt
layout = [
["trend", "trend", "share"],
["hist", "box", "share"],
]
fig, axd = plt.subplot_mosaic(layout, figsize=(9, 5), layout="constrained")
rng = np.random.default_rng(2)
sales = 100 + rng.normal(0, 8, 52).cumsum()
axd["trend"].plot(sales)
axd["trend"].set_title("Weekly sales")
axd["hist"].hist(sales, bins=12, color="C1")
axd["hist"].set_title("Distribution")
axd["box"].boxplot(sales)
axd["box"].set_title("Spread")
axd["share"].pie([45, 30, 25], labels=["Web", "Shop", "Phone"], autopct="%d%%")
axd["share"].set_title("Channels")
plt.show()
print("Panels:", sorted(axd))Panels: ['box', 'hist', 'share', 'trend']
The mosaic can also be one string with rows separated by ;, e.g. "AAB;CDB". A . leaves a cell empty.
Unequal sizes
width_ratios and height_ratios set relative sizes of columns and rows. They work with subplots and subplot_mosaic:
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(8)
x = rng.normal(0, 1, 400)
y = x * 0.5 + rng.normal(0, 0.7, 400)
fig, axd = plt.subplot_mosaic(
[["top", "."], ["main", "right"]],
width_ratios=[4, 1], height_ratios=[1, 4],
figsize=(6, 6), layout="constrained",
)
axd["main"].scatter(x, y, s=10, alpha=0.5)
axd["top"].hist(x, bins=25, color="C0")
axd["right"].hist(y, bins=25, color="C0", orientation="horizontal")
axd["top"].sharex(axd["main"])
axd["right"].sharey(axd["main"])
axd["main"].set(xlabel="x", ylabel="y")
plt.show()
w_main = axd["main"].get_position().width
w_right = axd["right"].get_position().width
print(f"main/right width ratio: {w_main / w_right:.1f}")main/right width ratio: 4.0
This "scatter with marginal histograms" shows both the relationship and each variable's distribution. ax.sharex(other) links the x axis of one Axes to another after creation.
GridSpec: slicing a grid
GridSpec is the lower-level tool behind both. You define a grid and then take slices of it, just like NumPy indexing:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 5), layout="constrained")
gs = fig.add_gridspec(3, 3)
ax_big = fig.add_subplot(gs[:2, :2]) # rows 0-1, cols 0-1
ax_side = fig.add_subplot(gs[:2, 2]) # rows 0-1, col 2
ax_bottom = fig.add_subplot(gs[2, :]) # row 2, all columns
t = np.linspace(0, 4 * np.pi, 300)
ax_big.plot(np.cos(t) * t, np.sin(t) * t)
ax_big.set_title("Spiral")
ax_side.barh(["a", "b", "c"], [3, 7, 5])
ax_side.set_title("Side")
ax_bottom.plot(t, np.sin(t) * t, color="C2")
ax_bottom.set_title("Bottom strip")
plt.show()
print("Grid:", gs.nrows, "x", gs.ncols, "| Axes:", len(fig.axes))Grid: 3 x 3 | Axes: 3
| Tool | Best for |
|---|---|
plt.subplots(r, c) |
Regular grids |
plt.subplot_mosaic(...) |
Irregular layouts that you can sketch as text; named panels |
fig.add_gridspec() + slices |
Fine control, nested grids |
fig.add_axes([...]) |
Insets and free placement |
Test yourself
In plt.subplot_mosaic([["A", "A"], ["B", "C"]]), what does panel A look like?
- A small square in the top left
- It spans the whole top row
- It spans the left column
- It is an error: names must be unique
How do you make the first column three times as wide as the second?
- width_ratios=[3, 1]
- figsize=(3, 1)
- gs[:3, 1]
- colspan=3
What is the recommended way to stop labels from overlapping in a new figure?
- Make the font tiny
- layout="constrained" when creating the figure
- Call plt.show() twice
- Use plt.grid()