# Complex Subplot Layouts in Matplotlib: subplot_mosaic and GridSpec

> Create uneven Matplotlib subplot layouts with plt.subplot_mosaic and GridSpec: spanning rows and columns, width_ratios, empty cells, mixed projections, nested grids.

Source: https://www.pythoncharts.com/matplotlib/matplotlib-subplot-mosaic-gridspec/ | Published: 2026-11-27 | Author: Alex Scott | Category: Matplotlib | Tags: matplotlib, subplots, subplot_mosaic, GridSpec, layout, dashboard

To make Matplotlib subplots of different sizes, use `plt.subplot_mosaic()` and draw the layout as a string such as `"AA;BC"`, where a repeated letter makes one panel span those cells. `GridSpec`, through `fig.add_gridspec()`, does the same job with NumPy-style slicing.

## Quick Example

One wide chart on top, two smaller ones below. `subplot_mosaic` returns a dictionary of Axes keyed by the names you used:

```python
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(31)
day = np.arange(1, 61)
visits = 900 + 8 * day + 140 * np.sin(2 * np.pi * day / 7) + rng.normal(0, 60, 60)
load_time = rng.lognormal(0.1, 0.35, 800)
sources = ["Search", "Direct", "Social", "Email"]
share = [52, 24, 15, 9]

fig, axd = plt.subplot_mosaic(
    """
    TT
    HS
    """,
    figsize=(9, 5.6),
    layout="constrained",
)

axd["T"].plot(day, visits, color="#0f766e")
axd["T"].set_title("Daily visits")

axd["H"].hist(load_time, bins=30, color="#7c3aed")
axd["H"].set_title("Page load time (s)")

axd["S"].barh(sources, share, color="#db2777")
axd["S"].invert_yaxis()
axd["S"].set_title("Traffic source (%)")
plt.show()
```

![Matplotlib dashboard with a wide daily visits line chart above a load time histogram and a traffic source bar chart](https://www.pythoncharts.com/matplotlib/matplotlib-subplot-mosaic-gridspec/images/matplotlib-subplot-mosaic-quick-example.png)

`layout="constrained"` keeps titles and tick labels from overlapping. The examples target Matplotlib 3.11.

## How the Mosaic String Works

Each character is one grid cell, and each line (or `;`-separated chunk) is one row.

| Mosaic | Result |
|---|---|
| `"AB;CD"` | Plain 2×2 grid |
| `"AA;BC"` | A spans the top row |
| `"AB;AC"` | A spans the left column |
| `"AAB;AAB;CC."` | Large A, tall B, wide C, one empty corner |

For readable keys, pass a list of lists with full names. A `"."` leaves a cell empty.

```python
layout = [
    ["trend", "trend", "trend"],
    ["detail", "detail", "total"],
    [".", "notes", "total"],
]

fig, axd = plt.subplot_mosaic(layout, figsize=(8, 5), layout="constrained")
for name, ax in axd.items():
    ax.text(0.5, 0.5, name, ha="center", va="center", fontsize=16,
            transform=ax.transAxes)
    ax.set_xticks([])
    ax.set_yticks([])
plt.show()
```

![Named subplot mosaic: trend across the top, detail and total below it, notes in the bottom middle, and an empty bottom left cell](https://www.pythoncharts.com/matplotlib/matplotlib-subplot-mosaic-gridspec/images/matplotlib-subplot-mosaic-named.png)

Every name must cover a rectangle. `plt.subplot_mosaic("AB;BA")` raises a `ValueError` that ends with `we found that the label 'B' specifies a non-rectangular or non-contiguous area.` Rows of different lengths, such as `"AAB;C"`, are also an error.

## Set Column Widths and Row Heights

`width_ratios` and `height_ratios` take one number per column or row. Here a scatter plot gets marginal histograms that are a quarter of its width and height:

```python
x = rng.normal(170, 9, 600)
y = 0.9 * x - 85 + rng.normal(0, 7, 600)

fig, axd = plt.subplot_mosaic(
    [["top", "."], ["main", "right"]],
    width_ratios=[4, 1],
    height_ratios=[1, 4],
    figsize=(6.5, 6),
    layout="constrained",
)
axd["main"].scatter(x, y, s=12, alpha=0.5, color="#0369a1")
axd["main"].set_xlabel("Height (cm)")
axd["main"].set_ylabel("Weight (kg)")
axd["top"].hist(x, bins=30, color="#0369a1")
axd["right"].hist(y, bins=30, orientation="horizontal", color="#0369a1")

axd["top"].sharex(axd["main"])
axd["right"].sharey(axd["main"])
axd["top"].tick_params(labelbottom=False)
axd["right"].tick_params(labelleft=False)
plt.show()
```

![Scatter plot of height and weight with marginal histograms above and to the right, built with width and height ratios](https://www.pythoncharts.com/matplotlib/matplotlib-subplot-mosaic-gridspec/images/matplotlib-subplot-mosaic-marginal.png)

`sharex()` lines each histogram up with the scatter. See [sharing axes between subplots](https://www.pythoncharts.com/matplotlib/matplotlib-shared-axes-subplots/) for the other ways to do this.

## Mix Polar and Regular Panels

`per_subplot_kw` passes keyword arguments to individual panels, keyed by name. Use `subplot_kw` instead to apply them to every panel.

```python
hours = np.linspace(0, 2 * np.pi, 24, endpoint=False)
requests = 40 + 30 * np.sin(hours - 2) + rng.normal(0, 3, 24)

fig, axd = plt.subplot_mosaic(
    "PLL",
    per_subplot_kw={"P": {"projection": "polar"}},
    figsize=(9, 3.4),
    layout="constrained",
)
axd["P"].bar(hours, requests, width=2 * np.pi / 24, color="#d97706")
axd["P"].set_theta_zero_location("N")
axd["P"].set_theta_direction(-1)
axd["P"].set_xticks(np.linspace(0, 2 * np.pi, 4, endpoint=False), ["0h", "6h", "12h", "18h"])
axd["P"].set_yticklabels([])
axd["L"].plot(np.arange(24), requests, "o-", color="#d97706")
axd["L"].set_xlabel("Hour")
axd["L"].set_ylabel("Requests per second")
plt.show()
```

![A polar bar chart of requests by hour next to a line chart of the same values](https://www.pythoncharts.com/matplotlib/matplotlib-subplot-mosaic-gridspec/images/matplotlib-subplot-mosaic-polar.png)

## The Same Layouts with GridSpec

`fig.add_gridspec()` creates a grid, and you place each panel by slicing it. This suits layouts computed in a loop or grids too large to type as a string.

```python
fig = plt.figure(figsize=(9, 5), layout="constrained")
gs = fig.add_gridspec(3, 4)

ax_big = fig.add_subplot(gs[:2, :3])     # rows 0-1, columns 0-2
ax_side = fig.add_subplot(gs[:, 3])      # every row, last column
bottom = [fig.add_subplot(gs[2, i]) for i in range(3)]

ax_big.plot(day, visits, color="#0f766e")
ax_big.set_title("gs[:2, :3]")
ax_side.hist(load_time, bins=30, orientation="horizontal", color="#7c3aed")
ax_side.set_title("gs[:, 3]")
for i, ax in enumerate(bottom):
    week = visits[i * 7:(i + 1) * 7]
    ax.bar(range(1, 8), week, color="#db2777")
    ax.set_title(f"gs[2, {i}]")
plt.show()
```

![GridSpec layout with a large line chart, a tall histogram on the right, and three small weekly bar charts along the bottom](https://www.pythoncharts.com/matplotlib/matplotlib-subplot-mosaic-gridspec/images/matplotlib-subplot-mosaic-gridspec.png)

## Nested Layouts with Subfigures

When two halves of a figure need separate grids and titles, split it with `fig.subfigures()` and call `subplot_mosaic` or `subplots` on each half.

```python
fig = plt.figure(figsize=(9, 4.2), layout="constrained")
left, right = fig.subfigures(1, 2, width_ratios=[2, 1])

axd = left.subplot_mosaic("AA;BC")
axd["A"].plot(day, visits, color="#0f766e")
axd["B"].hist(load_time, bins=20, color="#7c3aed")
axd["C"].bar(sources, share, color="#db2777")
axd["C"].tick_params(axis="x", labelrotation=45)
left.suptitle("Traffic", fontweight="bold")

axes = right.subplots(2, 1, sharex=True)
axes[0].plot(day, np.cumsum(visits) / 1000, color="#334155")
axes[0].set_title("Total visits (thousands)")
weekly = np.convolve(visits, np.ones(7) / 7, mode="valid")
axes[1].plot(day[6:], weekly, color="#334155")
axes[1].set_title("7-day average")
right.suptitle("Trend", fontweight="bold")
right.set_facecolor("#f1f5f9")
plt.show()
```

![Figure split into two subfigures: a traffic mosaic on the left and total and 7-day average charts stacked on a gray background on the right](https://www.pythoncharts.com/matplotlib/matplotlib-subplot-mosaic-gridspec/images/matplotlib-subplot-mosaic-subfigures.png)

## subplots, subplot_mosaic, or GridSpec?

| You need | Use |
|---|---|
| Equal-sized panels in rows and columns | `plt.subplots(2, 3)` |
| A few panels of different sizes | `plt.subplot_mosaic()` |
| Slicing, loops, or very fine grids | `fig.add_gridspec()` |
| Independent groups with their own titles | `fig.subfigures()` |
| A small chart inside another chart | `ax.inset_axes()` |

For regular grids, start with [Matplotlib subplots](https://www.pythoncharts.com/matplotlib/matplotlib-subplots/). If you build with the older `tight_layout()`, see [adjusting subplot spacing](https://www.pythoncharts.com/matplotlib/matplotlib-tight-layout-subplot-spacing/).

## Similar Topics

- [Matplotlib Subplots](https://www.pythoncharts.com/matplotlib/matplotlib-subplots/)
- [Changing the Figure and Plot Size in Matplotlib](https://www.pythoncharts.com/matplotlib/figure-size-matplotlib/)
- [Matplotlib Figure vs Axes](https://www.pythoncharts.com/matplotlib/matplotlib-figure-vs-axes/)
