Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 57 ยท Subplots and Layouts

Multiple Subplots

Put several charts in one Matplotlib figure with plt.subplots, index the axes array, share axes, hide empty panels, add a suptitle and control spacing.

One chart answers one question. Often you want to compare: the same metric across four regions, a signal next to its spectrum, a model's training loss beside its accuracy. Putting those charts in a single figure keeps them the same size, lets them share scales, and makes the comparison immediate. In Matplotlib, a figure can hold any number of Axes, and plt.subplots is the standard way to create a grid of them.

This lesson shows how to create the grid, how to address each panel, how to share limits so panels are comparable, and how to tidy up the spacing and titles. If the words Figure and Axes are still fuzzy, read Anatomy of a Figure first.

Creating a grid

plt.subplots(nrows, ncols) returns two things: the Figure and the Axes. With more than one panel, the Axes come as a NumPy array whose shape matches the grid.

Python A 2 by 2 grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

axes[row, col] addresses a panel, counting from the top-left. Each panel is an ordinary Axes with every method you already know: plot, set_title, set_xlabel and so on.

The shape of the axes array

The return value changes shape depending on the grid, and that is a classic source of confusing errors.

Call axes is
plt.subplots() a single Axes object
plt.subplots(1, 3) 1D array of 3
plt.subplots(3, 1) 1D array of 3
plt.subplots(2, 3) 2D array of shape (2, 3)

With one row or one column you index with a single number, axes[2], and axes[0, 2] fails. If you want the same indexing no matter what, pass squeeze=False: you then always get a 2D array, even for a single panel.

Looping over the panels

Writing axes[0, 0], axes[0, 1], and so on gets repetitive. Flatten the array to one dimension and loop. axes.flat or axes.ravel() both work (note that flatten() also works on the array but makes a copy; the Axes objects themselves are the same).

Python One loop, six panels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A loop also keeps panels consistent: any style you apply inside the loop applies to all of them. When your panels come from data, zip the Axes with the data: for ax, (name, group) in zip(axes.flat, groups):.

Use fig.suptitle("...") for the title of the whole figure, and ax.set_title("...") for each panel. The suptitle sits above the grid; call fig.tight_layout() or use layout="constrained" so that it does not collide with panel titles.

Sharing axes

When panels show the same quantity, they should use the same scale. Otherwise a reader compares bars of different heights that mean different things. sharex=True and sharey=True link the limits, so zooming or setting limits on one changes all. With sharey=True only the left column keeps its tick labels, which removes clutter.

Python sharex and sharey

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You can also pass sharex="col" or sharey="row" to share only within columns or rows, which is right for grids where each row has its own unit. Use shared and twin axes when two quantities with different units must sit in the same panel.

Spacing

fig.tight_layout() adjusts the spacing so that labels do not overlap. A newer, more robust option is to ask for the layout engine when you create the figure:

Python
fig, axes = plt.subplots(2, 2, figsize=(7, 5), layout="constrained")

Constrained layout also handles colorbars and suptitle more gracefully. For manual control use fig.subplots_adjust(wspace=0.3, hspace=0.4), where the values are fractions of an average panel size. Pick one approach per figure: the layout engines and manual adjustments fight each other. Figure Size, DPI and Layout covers the engines in more depth.

Hiding empty panels

If you need seven panels you must ask for a 2 by 4 grid, which leaves one empty frame. Switch off the unused ones with ax.set_visible(False) (the frame and ticks disappear) or ax.axis("off").

Python Seven panels in a 2 by 4 grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

zip stops at the shorter list, so the loop that draws only uses seven Axes, and the second loop hides the rest. Be careful not to hide a panel that the other panels share an axis with, or ticks may vanish. If that happens, hide the shared panel's content with ax.axis("off") instead.

Shared labels: supxlabel and supylabel

When a grid of panels all use the same units, repeating "time (s)" under every panel is noise. fig.suptitle adds one title for the whole figure; its companions fig.supxlabel and fig.supylabel add one x label centred under the whole figure and one y label centred beside it. Pair them with sharex=True, sharey=True, and label only what is not shared.

Python One x label and one y label for the whole grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With layout="constrained" the layout engine makes room for the super labels automatically. Without it, you may need to call fig.tight_layout() or adjust fig.subplots_adjust(left=...) so the labels do not overlap the tick labels.

The state-machine way: plt.subplot

Before plt.subplots existed, everyone made grids with plt.subplot(nrows, ncols, index), and a great deal of existing code (and many tutorials) still does. It does not create the whole grid. Each call creates or selects one panel and makes it the current Axes, and later plt.plot, plt.title and friends draw there. The index counts from 1, left to right and then top to bottom.

  • plt.subplot(2, 2, 1) is the top left panel of a 2 by 2 grid. With single-digit numbers you may write it as one three-digit number: plt.subplot(221).
  • A panel can span cells if you mix grids: after a (2, 2, ...) grid, plt.subplot(2, 1, 2) creates one panel for the entire bottom row.
  • Extra keywords such as facecolor=, projection="polar", sharex= or label= go to the new Axes.
  • Calling plt.subplot again with the same arguments gives you back the existing panel.
Python plt.subplot: three panels the old way

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The figure ends up with three Axes, and the current one is the last you created. That hidden "current" state is the weakness of this style: in longer scripts you lose track of which panel receives the next call. For new code prefer fig, axes = plt.subplots(...) or fig.add_subplot(...) and call methods on the Axes objects, as explained in pyplot versus the object-oriented API.

The legacy way: subplot2grid

Older tutorials and a lot of existing code use plt.subplot2grid(shape, loc, rowspan=1, colspan=1). You declare the grid size, then say where each Axes starts and how many rows and columns it spans. It is the older relative of GridSpec and subplot_mosaic, which are the better choice for new code (they are named, work with the object-oriented API and handle the spacing well).

Python subplot2grid with spans

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same layout with the modern API is fig.add_subplot(gs[0, :]) after gs = fig.add_gridspec(3, 3), or one line of text with fig.subplot_mosaic("AAA;BBC;BBD"). Read subplot2grid code when you meet it, but write subplot_mosaic yourself.

Clearing and closing: clf, cla and close

Figures and Axes stay in memory until you release them, which matters when you draw many charts in a loop or a long notebook session. Three methods do three different things:

Call What it removes Keeps
ax.cla() (or ax.clear()) everything drawn on one Axes, plus its labels and limits the Axes itself and the figure
fig.clf() (or fig.clear()) every Axes and text in the figure the empty Figure object
plt.close(fig) the figure completely, freeing its memory nothing; you cannot draw on it again

plt.close("all") closes every open figure, and plt.close() closes the current one. The pyplot interface keeps its own list of figures, so a figure created with plt.figure() or plt.subplots() is not freed by simply reassigning the variable. A loop that creates 500 charts without closing them eventually warns "More than 20 figures have been opened". plt.get_fignums() lists the numbers of the open figures, which is a handy check.

Python cla, clf and close compared

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Prefer creating a new figure for each chart and closing it over reusing one figure with clf(). Reuse is a little faster, but leftover state (shared axes, colorbars, titles) from the previous drawing is a classic source of confusing bugs.

Summary of the pattern

The version that scales is: create the grid with a layout engine, loop over axes.flat, label the outer panels only, and add a figure-level title.

flowchart LR
    A["plt.subplots(r, c)"] --> B["axes.flat loop"]
    B --> C["plot + set_title<br/>per panel"]
    C --> D["hide unused axes"]
    D --> E["suptitle + layout"]

The usual recipe for a grid of similar charts.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does plt.subplots(1, 3) return as its second value?

    With a single row or column the extra dimension is squeezed away, so you index with one number such as axes[2]. Use squeeze=False to always get a 2D array.
  2. 2. What is the effect of sharey=True?

    Shared axes link their limits so panels are directly comparable, and Matplotlib drops redundant tick labels on inner panels.
  3. 3. How do you set one title for the whole figure?

    suptitle is the figure-level title; set_title belongs to a single Axes.
  4. 4. You asked for a 2 by 4 grid but drew seven charts. What removes the empty frame?

    Unused Axes still exist and draw a frame. Hide them with set_visible(False) or axis('off').

Summary

  • fig, axes = plt.subplots(nrows, ncols) creates a grid; axes[row, col] addresses a panel.
  • The axes array is 1D for a single row or column and a single object for one panel; squeeze=False always gives 2D.
  • Loop over axes.flat (zipped with your data) instead of writing every index.
  • sharex and sharey make panels comparable and remove repeated tick labels.
  • layout="constrained" or tight_layout() handles spacing; fig.suptitle titles the whole figure.
  • Hide unused panels with set_visible(False).
  • fig.supxlabel and fig.supylabel label a whole grid once; subplot2grid is the legacy spanning API (prefer subplot_mosaic); ax.cla() empties one Axes, fig.clf() empties a figure and plt.close(fig) frees it.

Next, build uneven layouts in GridSpec and subplot_mosaic.