typestar

Grids of axes in Python

subplots returns an array of axes you can index like any other.

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)
figure, axes = plt.subplots(nrows=2, ncols=2, figsize=(7, 5), sharex=True)

for ax, (name, values) in zip(axes.ravel(), [
    ("sin", np.sin(x)), ("cos", np.cos(x)),
    ("sin squared", np.sin(x) ** 2), ("damped", np.sin(x) * np.exp(-x / 5)),
]):
    ax.plot(x, values)
    ax.set_title(name, fontsize=9)

figure.tight_layout()
print(axes.shape)
figure.savefig("grid.png")

How it works

  1. nrows and ncols shape the grid.
  2. sharex links the axes so zooming one moves them all.
  3. tight_layout stops the labels colliding.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
484
Tokens
187
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 112 seconds.

Type this snippet

Step 2 of 4 in Figures & axes, step 2 of 14 in Plotting with matplotlib.

← Previous Next →