Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 57 ยท Subplots and Layouts

GridSpec and subplot_mosaic

Build uneven Matplotlib layouts with GridSpec, spanning rows and columns, width_ratios, subplot_mosaic strings, nested grids, inset axes and a dashboard.

plt.subplots(2, 3) gives you a grid of equal cells. Real figures are rarely that tidy. A dashboard wants one wide chart across the top and two small ones below. A scatter plot wants thin histograms along its edges. A map wants a narrow colorbar strip. For all of these you need panels of different sizes, and Matplotlib has two tools: GridSpec, which is explicit, and subplot_mosaic, which lets you draw the layout as text.

This lesson builds on Multiple Subplots. You will make uneven grids, span cells, set size ratios, nest grids, add a small inset chart inside another one, and finish with a dashboard layout.

Three ways to lay out a figure

subplots Equal cells. Fast and simple.
GridSpec Slice a grid to span cells.
subplot_mosaic Draw the layout as letters.

Start simple; reach for the next tool only when the layout needs it.

1 / 2

GridSpec: slice the grid

fig.add_gridspec(nrows, ncols) makes a grid description without creating any panels. You then create an Axes by slicing it, exactly like a NumPy array. A slice that covers several cells makes a panel that spans them.

Python A panel that spans a whole row

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 slice syntax is gs[rows, cols], so gs[0, :] is the whole first row, gs[1:, 0] is the first column from row 1 down, and gs[:2, :2] is a 2 by 2 block. Each add_subplot call returns one Axes.

Unequal sizes with ratios

width_ratios and height_ratios set the relative size of columns and rows. A ratio of [4, 1] means the first column is four times as wide as the second. This is the standard way to build a scatter plot with marginal histograms.

Python Scatter with marginal histograms

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.

Sharing the axes (sharex=ax_main) keeps the histogram bins aligned with the scatter points. The tick_params(labelbottom=False) calls remove duplicate tick labels, as you would with sharex in a regular grid. Histograms themselves are covered in Histograms and Distributions.

GridSpec parameters in one place

GridSpec(nrows, ncols, ...) takes the keyword arguments that control all the spacing, and they are worth knowing together:

Keyword Meaning
figure the Figure the grid belongs to (needed for left, right, top and bottom)
wspace, hspace gaps between columns and rows, as a fraction of the average panel size
width_ratios, height_ratios relative sizes of the columns and rows
left, right, top, bottom the outer border of the whole grid, as fractions of the figure (0 to 1)

Slicing the grid selects cells: gs[0, :] is the whole first row, gs[1, 1:] is row 1 from column 1 to the end. gs.get_geometry() gives (nrows, ncols), and the ratio getters return what you set. The next example uses every keyword at once.

Python Every GridSpec keyword

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 first column of the bottom row is twice as wide as each of the other two columns, and the bottom row is twice as tall as the top row. The top panel spans all three columns, so its width equals the grid width (0.89 of the figure here, because left=0.08 and right=0.97).

subplot_mosaic: draw the layout

subplot_mosaic takes a text picture. Each letter names a panel; repeated letters (that form a rectangle) merge into one wide or tall panel; a dot is an empty cell. It returns the figure and a dictionary from label to Axes, so you address panels by name rather than by index.

Python A mosaic layout from a string

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 rows of the string must be the same length, and each label must form a single rectangle. A mosaic is the most readable way to describe a layout: the text looks like the figure. You can pass width_ratios and height_ratios here too. For a quick layout with empty cells, use . (default empty_sentinel), for example "AA.\nBCD".

You can also give a nested list instead of a string, and nest lists to build sub-layouts: [["A", ["B", "C"]]] puts B and C stacked in the right half.

Nested grids

A panel can itself hold a smaller grid. gs[0, 0].subgridspec(nrows, ncols) makes a grid inside one cell of another. This is useful when one section of a figure needs a tight cluster of small charts, while the rest stays large.

Python A subgrid inside one cell

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.

Insets

An inset is a small Axes placed on top of another. ax.inset_axes([x0, y0, width, height]) takes a box in axes fractions: [0.6, 0.55, 0.35, 0.35] means start 60% across and 55% up, then take 35% of the width and height. An inset is perfect for a zoomed region or a distribution beside a time series.

Python A zoomed inset

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.

indicate_inset_zoom draws the rectangle on the parent and the connecting lines, so the reader knows what the inset shows.

A dashboard layout

Combine the tools for a small dashboard: a wide trend on top, two panels below, and one panel for a headline number. A mosaic keeps it readable. Panels that hold only text can switch off their axes and write with ax.text.

Python Mini dashboard

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.

Use layout="constrained" with GridSpec and mosaic layouts. It reflows spacing as panels have different sizes, which tight_layout() often handles badly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does gs[0, :] select in a GridSpec?

    GridSpec slices like a NumPy array: the first index is the row, the second is the column, and a colon means all.
  2. 2. What does subplot_mosaic return?

    Each panel is addressed by its label, so you write axd['A'] and not axes[0, 1].
  3. 3. In the layout string 'AAB\nCDB', what is B?

    Repeated letters that form a rectangle merge into one panel. B occupies the last column of both rows.
  4. 4. What units does ax.inset_axes([0.6, 0.5, 0.3, 0.3]) use?

    The box is (x0, y0, width, height) as fractions of the parent Axes, so it stays in place whatever the data limits are.

Summary

  • fig.add_gridspec(rows, cols, width_ratios=, height_ratios=) describes a grid; slice it to create spanning panels.
  • Ratios give panels unequal sizes, as in a scatter plot with marginal histograms.
  • plt.subplot_mosaic("AAB\nCDB") builds a layout from text and returns a dict of Axes by label.
  • subgridspec nests a grid inside one cell of another.
  • ax.inset_axes([x, y, w, h]) adds a small chart inside a chart; indicate_inset_zoom links it to the region.
  • Prefer layout="constrained" for uneven layouts.

Next, learn how to plot two scales together in Shared, Twin and Secondary Axes.