Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Combining Plots with Subplots

DS 2023 | Communicating with Data

Overview

So far in this course, we have seen many figures with several plots side by side.

This is a powerful visual device: aligning plots that depict the same data but through different lenses.

This notebook looks closely at how subplotting works.

Recall that in Matplotlib, a figure is the whole image, the canvas.

An axes is one plotting region inside the figure, with its own x axis, y axis, and data.

A figure can hold any number of axes.

When it holds several axes, we call them subplots.

We also call the regions in the figure where the plots live panels.

Matplotlib gives us two main ways to define and arrange panels:

  • plt.subplots() arranges axes in a regular grid and returns them as an array, indexed by row and column.

  • plt.subplot_mosaic() lets us draw the layout with labels and returns the axes as a dictionary, indexed by name.

The second method was added in Matplotlib 3.4, and it makes irregular layouts much easier.

Use Cases

Small multiples: the same plot for each group, such as one histogram per penguin species or one line per country.

Different views of the same data: a scatter plot with histograms of each variable along its edges.

Before and after: raw data next to transformed data, or one parameter setting next to another.

Summary figures: one large plot that tells the main story, with smaller plots that support it, as in a report or a poster.

Juxtaposition: visually aligning different plots that elucidate different aspects of the same structure.

Set Up

We will work with familiar data.

Creating Subplots from Scratch

Let’s start by placing axes by hand.

A figure has its own coordinate system, running from 0 to 1 in each direction, with (0,0)(0, 0) at the bottom left.

fig.add_axes() takes a rectangle in these coordinates, written as [lower_x, lower_y, width, height], and puts an axes there.

<Figure size 800x400 with 2 Axes>

Every layout method in Matplotlib does exactly this, ultimately.

It works out a rectangle for each axes and places it on the figure.

Let’s draw two real plots this way.

<Figure size 1000x400 with 2 Axes>

This gives us complete control.

But it is tedious.

We had to compute every margin and every width ourselves, and if we add a third plot, we must recompute all of them.

What we really want is to say what the arrangement is, and let Matplotlib work out the rectangles.

Using plt.subplots()

plt.subplots() takes a number of rows and a number of columns.

It returns two things: the figure, and the axes.

<Figure size 900x500 with 6 Axes>

The axes come back as a NumPy array with the same shape as the grid.

(2, 3)

So we reach each axes by its row and column, counting from 0.

ax[0, 0] is the top left, and ax[1, 2] is the bottom right.

Let’s label every cell with its index so we can see the pattern.

<Figure size 900x500 with 6 Axes>

A simple example

Let’s draw one histogram of body mass for each species.

There are three species, so we create a figure with one row of three axes.

Even though we know we can use subplots with Pandas, we will use a loop to demonstrate the use of pre-defined axes.

<Figure size 1000x300 with 3 Axes>

Notice that the parameters sharex=True and sharey=True give every axes the same x range and the same y range.

Sharing axes allows us to compare the panels directly.

For example, we can see that Gentoos are heavier than the other two species because its mass is farther to the right of the scale shared by all three plots.

Subplots with Pandas

As mentioned, Pandas’ plot method has a subplots argument, which handles the suplotting for you with arguments passed directly to plot.

Note that since we didn’t use plt.subplots, we didn’t get a fig object to use to provide a figure-level x axis label.

Instead, we use plt.gcf to get the current figure.

<Figure size 1000x300 with 3 Axes>

Pandas’ plotting methods can also take an ax parameter.

So we can create the grid with Matplotlib and let Pandas fill each axes.

Here is the airline passengers table from Heatmaps, drawn two ways.

<Figure size 1200x400 with 2 Axes>

This division of labor is the one we will use throughout: Matplotlib builds the layout, and Pandas draws the plots.

Flattening the grid

When the grid has more than one row, it is often easier to loop over a flat list of axes.

ax.flat walks through the array row by row.

Here is life expectancy for each of the six countries in healthexp, in a 2 × 3 grid.

<Figure size 1200x600 with 6 Axes>

What do you notice when you compare the USA panel with Japan’s?

Because the y axes are shared, the comparison is honest.

Where plt.subplots() gets awkward

Left-over panels

plt.subplots() is perfect for regular grids, i.e. where each row has the same number of axes.

But real figures are often not regular.

If we have five plots, a 2 × 3 grid leaves one axes empty, and Matplotlib still draws its frame.

<Figure size 1200x600 with 6 Axes>

The sixth axes is empty, but its frame and tick labels are still there.

We have to remember to remove it ourselves, with set_axis_off().

And if we later add or drop a measure, we have to rethink the grid.

<Figure size 1200x600 with 6 Axes>

Spanning cells

Suppose we want one wide plot on top and two smaller plots below it.

That layout is not a regular grid, so plt.subplots() cannot make it.

One solution is to use a GridSpec object, which describes the grid separately from the axes.

GridSpect allow us to place an axes on a slice of the grid, using the same slicing syntax as a NumPy array.

<Figure size 1000x600 with 3 Axes>

This works, but notice how the structure of the code does not mirror the structure of the figure.

To understand the layout, we have to read the slices and picture the result in our heads.

Indexing by position

Finally, ax[1, 0] tells us where an axes is, but not what it shows.

If we rearrange the figure, every index in the code must change with it, and a mistake puts a plot in the wrong place without any error.

A better way: using plt.subplot_mosaic()

plt.subplot_mosaic() solves all three problems with one idea.

Instead of giving the number of rows and columns, we draw the layout as a list of lists, one inner list per row.

Each entry is a label, and each label becomes one axes.

<Figure size 800x500 with 4 Axes>

The axes come back as a dictionary, not an array.

Its keys are the axes labels.

{'A': <Axes: label='A'>, 'B': <Axes: label='B'>, 'C': <Axes: label='C'>, 'D': <Axes: label='D'>}

So we reach each axes by name: axd['C'], not ax[1, 0].

If you use single characters for labels, we can write the layout as a string instead.

Rows are separated by semicolons, or by new lines.

<Figure size 800x500 with 4 Axes>

Spanning cells

To make an axes span several cells, we repeat its label.

Here is the wide-top layout we built with GridSpec.

<Figure size 1000x600 with 3 Axes>

Now the code looks like the figure.

T fills both cells of the top row, so it becomes one wide axes.

A label’s cells must form a rectangle.

An L-shaped region, for example, raises an error.

Leaving cells empty

A period, '.', marks a cell with no axes.

This solves the leftover-cell problem: we simply leave the cell out of the drawing.

<Figure size 1200x600 with 5 Axes>

Notice that the labels are now the column names themselves.

Labels can be any strings, so they can describe what each axes shows.

This is sometimes called semantic layout: the code names the plots by their meaning, not their position.

We also passed layout='constrained'.

This asks Matplotlib to fit titles, labels, and colorbars without overlap, like plt.tight_layout(), but it is applied every time the figure is drawn.

It works with plt.subplots() too.

Sizing rows and columns

By default, every row has the same height and every column the same width.

width_ratios and height_ratios change that.

They give the relative sizes, so [3, 1] makes the first column three times as wide as the second.

<Figure size 1000x500 with 3 Axes>

Examples

A simple example

Let’s make a summary figure for healthexp.

The main story is health spending over time, so it gets the wide top panel.

Two smaller panels support it: spending in the most recent year, and life expectancy against spending.

<Figure size 1200x800 with 3 Axes>

Each panel was drawn by Pandas or Matplotlib exactly as it would be on its own.

All we changed was the ax= argument.

The bottom right panel needs no legend of its own: Matplotlib assigns colors to the countries in the same order in both panels, so the top legend serves for both.

Notice how the bottom right panel puts the top panel’s story in context.

The USA spends far more than any other country, but its life expectancy is the lowest of the six.

A more complex example

A common figure in exploratory analysis is a scatter plot with a histogram of each variable along its edges.

These edge plots are called marginal distributions, because they sit in the margins.

The layout has a large main panel, a short panel above it, a narrow panel to its right, and an empty corner.

With a mosaic, we can draw exactly that.

<Figure size 800x800 with 3 Axes>

Each marginal histogram lines up with the axis it describes.

  • That is what sharex() and sharey() do: they tie one axes’ scale to another’s.

  • The right histogram uses orientation='horizontal' so that its bars run along the y axis.

Now look at the three views together.

  • In the top margin, Chinstraps and Gentoos overlap in bill length.

  • In the right margin, Adelies and Chinstraps overlap in bill depth.

  • Only the scatter plot, which uses both variables, separates all three species.

When Subplots Mislead

A figure with several panels invites readers to compare them.

So the design choices of the layout become claims about the data.

Independent scales

By default, each axes chooses its own range to fit its own data.

Let’s draw health spending by country without shared y axes.

<Figure size 1200x600 with 6 Axes>

Every country seems to climb to about the same height.

But read the y axes: the tops range from a few thousand dollars to more than ten thousand.

The panels look alike only because each was stretched to fill its own box.

Now let’s share the y axis.

<Figure size 1200x600 with 6 Axes>

Now the USA stands out immediately.

Other pitfalls

  • Size implies importance. A large panel draws the eye first. Give the most space to the main story, not to whichever plot happened to come first.

  • Position implies order. Readers scan left to right and top to bottom. Arrange panels in a meaningful order, such as by time, by value, or by a natural sequence of categories.

  • Inconsistent encodings. If a group is blue in one panel, it should be blue in every panel. Reusing a dictionary like species_colors keeps colors tied to groups, not positions.

  • Empty and duplicated labels. Repeating the same axis label in every panel adds clutter. Use fig.supxlabel() and fig.supylabel() for labels the panels share.

  • Too many panels. Small multiples work because each panel is simple. If each panel needs close study, the figure may be better as several figures.

Summary

  • A figure is the canvas, and each axes is one plotting region inside it. Several axes in one figure are subplots.

  • Every layout method computes a rectangle for each axes, as fig.add_axes() does by hand.

  • plt.subplots(rows, cols) makes a regular grid and returns the axes as an array indexed by position.

  • plt.subplot_mosaic() takes a drawing of the layout and returns the axes as a dictionary indexed by label.

  • In a mosaic, repeat a label to span cells, and use '.' for an empty cell.

  • Matplotlib builds the layout, and Pandas fills each axes through its ax= parameter.

  • Share axes when panels show the same measurement, so that comparisons are honest.

TaskCode
Regular gridfig, ax = plt.subplots(2, 3)
Shared scalesplt.subplots(2, 3, sharex=True, sharey=True)
Loop over a gridfor a in ax.flat:
Hide an unused axesax[1, 2].set_axis_off()
Drawn layoutfig, axd = plt.subplot_mosaic([['A', 'A'], ['B', 'C']])
String layoutplt.subplot_mosaic('AA;BC')
Empty cell'.' in the layout
Relative sizeswidth_ratios=[3, 1], height_ratios=[1, 4]
Avoid overlapslayout='constrained'
Tie one axes to anotheraxd['top'].sharex(axd['main'])
Draw with Pandasdf.plot(ax=axd['trend'])
Shared labelsfig.supxlabel(...), fig.supylabel(...)