TExcelTAD
Home › Matplotlib › Matplotlib Subplot

Matplotlib Subplot

Often you want several related charts side by side: the same measure for different groups, or different measures over the same time span. Subplots divide one figure into a grid of separate Axes.

plt.subplot(rows, cols, index)

plt.subplot() creates one Axes in a grid and makes it current. The index starts at 1 and counts left to right, top to bottom:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 100)

plt.subplot(1, 2, 1)       # 1 row, 2 columns, first plot
plt.plot(x, np.sin(x))
plt.title("sin")

plt.subplot(1, 2, 2)       # 1 row, 2 columns, second plot
plt.plot(x, np.cos(x), color="C1")
plt.title("cos")

plt.show()
print("Axes in the figure:", len(plt.gcf().axes))
Axes in the figure: 2

You can also write the three numbers as one: plt.subplot(122) is the same as plt.subplot(1, 2, 2) (only for grids smaller than 10×10).

A 2×2 grid

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1, 11)
plt.figure(figsize=(8, 6))

for i, (power, color) in enumerate([(1, "C0"), (2, "C1"), (0.5, "C2"), (-1, "C3")], start=1):
    plt.subplot(2, 2, i)
    plt.plot(x, x ** float(power), color=color, marker=".")
    plt.title(f"$y = x^{{{power}}}
quot;) plt.suptitle("Four power functions") plt.tight_layout() plt.show() print([ax.get_title() for ax in plt.gcf().axes])
['$y = x^{1}
  

, '$y = x^{2}
  

, '$y = x^{0.5}
  

, '$y = x^{-1}
  

]

plt.tight_layout() adjusts the spacing so titles and tick labels of neighbouring subplots don't overlap. Try removing it to see the difference.

plt.subplots(): all at once

The function with an s, plt.subplots(nrows, ncols), creates the whole grid in one call and returns the figure plus an array of Axes. You then draw on each Axes with its own methods (ax.plot, ax.set_title, …). This is the style most Matplotlib code uses:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

months = np.arange(1, 13)
temp = np.array([2, 3, 7, 11, 15, 18, 20, 20, 16, 11, 6, 3])
rain = np.array([62, 48, 55, 50, 58, 64, 70, 75, 66, 72, 80, 74])

fig, axes = plt.subplots(2, 1, figsize=(6, 5), sharex=True)
axes[0].plot(months, temp, color="C3", marker="o")
axes[0].set_ylabel("°C")
axes[0].set_title("Temperature")

axes[1].bar(months, rain, color="C0")
axes[1].set_ylabel("mm")
axes[1].set_title("Rainfall")
axes[1].set_xlabel("Month")

fig.tight_layout()
plt.show()

print("axes array shape:", axes.shape)
print("warmest month:", months[temp.argmax()], "| wettest month:", months[rain.argmax()])
axes array shape: (2,)
warmest month: 7 | wettest month: 11

sharex=True gives both plots the same x axis, so zooming or limiting one also affects the other, and the inner tick labels are hidden. There is also sharey=True.

Function Returns Style
plt.subplot(r, c, i) one Axes, made current pyplot, one panel at a time
plt.subplots(r, c) (fig, axes) object-oriented, whole grid
fig.add_subplot(r, c, i) one Axes object-oriented, one at a time

Looping over a grid

For a 2-D grid, axes is a 2-D NumPy array. axes.flat iterates over all of them in reading order, which keeps loops short:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(7)
fig, axes = plt.subplots(2, 3, figsize=(9, 5), sharey=True)

for n, ax in enumerate(axes.flat, start=1):
    walk = rng.normal(0, 1, 50).cumsum()
    ax.plot(walk, lw=1)
    ax.set_title(f"Walk {n}")

fig.suptitle("Six random walks")
fig.tight_layout()
plt.show()

print("Number of panels:", axes.size)
print("Shared y limits:", [round(float(v), 2) for v in axes[0, 0].get_ylim()])
Number of panels: 6
Shared y limits: [-18.04, 5.41]

The random numbers come from a seeded generator (default_rng(7)), so the walks are the same every time you run the example.

Test yourself

In plt.subplot(2, 3, 4), where does the new Axes go?

  1. Row 2, column 3
  2. Row 2, column 1
  3. Row 1, column 4
  4. It is an error; the index starts at 0

What does fig, axes = plt.subplots(2, 2) return as axes?

  1. A list of 4 figures
  2. A 2×2 NumPy array of Axes
  3. A single Axes
  4. A dictionary

What is the main job of tight_layout()?

  1. Make the figure smaller
  2. Remove the axes
  3. Adjust spacing so labels and titles don't overlap
  4. Share the x axis