Arranging Multiple Axes in A Figure - Matplotlib 3.8.4 Documentation
Arranging Multiple Axes in A Figure - Matplotlib 3.8.4 Documentation
4 documentation
Note
Matplotlib uses Axes to refer to the drawing area that contains data, x- and y-axis, ticks, labels, title, etc. See Parts of a
Figure for more details. Another term that is often used is "subplot", which refers to an Axes that is in a grid with other
Axes objects.
Overview
The primary function used to create figures and a grid of Axes. It creates and places all Axes on the figure at once, and
returns an object array with handles for the Axes in the grid. See Figure.subplots .
or
subplot_mosaic
A simple way to create figures and a grid of Axes, with the added flexibility that Axes can also span rows or columns. The
Axes are returned in a labelled dictionary instead of an array. See also Figure.subplot_mosaic and Complex and semantic
figure composition (subplot_mosaic).
Sometimes it is natural to have more than one distinct group of Axes grids, in which case Matplotlib has the concept of
SubFigure :
SubFigure
Underlying tools
Underlying these are the concept of a GridSpec and a SubplotSpec :
GridSpec
Specifies the geometry of the grid that a subplot will be placed. The number of rows and number of columns of the grid
need to be set. Optionally, the subplot layout parameters (e.g., left, right, etc.) can be tuned.
SubplotSpec
subplot or Figure.add_subplot
Adds a single subplot on a figure, with 1-based indexing (inherited from Matlab). Columns and rows can be spanned by
specifying a range of grid cells.
subplot2grid
Similar to pyplot.subplot , but uses 0-based indexing and two-d python slicing to choose cells.
As a simple example of manually adding an axes a, lets add a 3 inch x 2 inch Axes to a 4 inch x 3 inch figure. Note that the
location of the subplot is defined as [left, bottom, width, height] in figure-normalized units:
w, h = 4, 3
margin = 0.5
fig = plt.figure(figsize=(w, h), facecolor='lightblue')
ax = fig.add_axes([margin / w, margin / h, (w - 2 * margin) / w,
(h - 2 * margin) / h])
We will annotate a lot of Axes, so let's encapsulate the annotation, rather than having that large piece of annotation code every
time we need it:
The same effect can be achieved with subplot_mosaic , but the return type is a dictionary instead of an array, where the user can
give the keys useful meanings. Here we provide two lists, each list representing a row, and each element in the list a key
representing the column.
https://matplotlib.org/stable/users/explain/axes/arranging_axes.html 3/11
19/04/2024 Arranging multiple Axes in a Figure — Matplotlib 3.8.4 documentation
One way to address this is to change the aspect of the figure to be close to the aspect ratio of the Axes, however that requires
trial and error. Matplotlib also supplies layout="compressed" , which will work with simple grids to reduce the gaps between
Axes. (The mpl_toolkits also provides ImageGrid to accomplish a similar effect, but with a non-standard Axes class).
https://matplotlib.org/stable/users/explain/axes/arranging_axes.html 4/11
19/04/2024 Arranging multiple Axes in a Figure — Matplotlib 3.8.4 documentation
See below for the description of how to do the same thing using GridSpec or subplot2grid .
https://matplotlib.org/stable/users/explain/axes/arranging_axes.html 5/11
19/04/2024 Arranging multiple Axes in a Figure — Matplotlib 3.8.4 documentation
fig = plt.figure(layout="constrained")
subfigs = fig.subfigures(1, 2, wspace=0.07, width_ratios=[1.5, 1.])
axs0 = subfigs[0].subplots(2, 2)
subfigs[0].set_facecolor('lightblue')
subfigs[0].suptitle('subfigs[0]\nLeft side')
subfigs[0].supxlabel('xlabel for subfigs[0]')
axs1 = subfigs[1].subplots(3, 1)
subfigs[1].suptitle('subfigs[1]')
subfigs[1].supylabel('ylabel for subfigs[1]')
https://matplotlib.org/stable/users/explain/axes/arranging_axes.html 6/11
19/04/2024 Arranging multiple Axes in a Figure — Matplotlib 3.8.4 documentation
It is also possible to nest Axes using subplot_mosaic using nested lists. This method does not use subfigures, like above, so lacks
the ability to add per-subfigure suptitle and supxlabel , etc. Rather it is a convenience wrapper around the subgridspec
method described below.
inner = [['innerA'],
['innerB']]
outer = [['upper left', inner],
['lower left', 'lower right']]
https://matplotlib.org/stable/users/explain/axes/arranging_axes.html 7/11
19/04/2024 Arranging multiple Axes in a Figure — Matplotlib 3.8.4 documentation
The following examples show how to use low-level methods to arrange Axes using GridSpec objects.
https://matplotlib.org/stable/users/explain/axes/arranging_axes.html 8/11
19/04/2024 Arranging multiple Axes in a Figure — Matplotlib 3.8.4 documentation
These spacing parameters can also be passed to subplots and subplot_mosaic as the gridspec_kw argument.
fig = plt.figure(layout="constrained")
gs0 = fig.add_gridspec(1, 2)
gs00 = gs0[0].subgridspec(2, 2)
gs01 = gs0[1].subgridspec(3, 1)
for a in range(2):
for b in range(2):
ax = fig.add_subplot(gs00[a, b])
annotate_axes(ax, f'axLeft[{a}, {b}]', fontsize=10)
if a == 1 and b == 1:
ax.set_xlabel('xlabel')
for a in range(3):
ax = fig.add_subplot(gs01[a])
annotate_axes(ax, f'axRight[{a}, {b}]')
if a == 2:
ax.set_ylabel('ylabel')
fig.suptitle('nested gridspecs')
Here's a more sophisticated example of nested GridSpec: We create an outer 4x4 grid with each cell containing an inner 3x3 grid
of Axes. We outline the outer 4x4 grid by hiding appropriate spines in each of the inner 3x3 grids.
for a in range(4):
for b in range(4):
# gridspec inside gridspec
inner_grid = outer_grid[a, b].subgridspec(3, 3, wspace=0, hspace=0)
axs = inner_grid.subplots() # Create all subplots for the inner grid.
for (c, d), ax in np.ndenumerate(axs):
ax.plot(*squiggle_xy(a + 1, b + 1, c + 1, d + 1))
ax.set(xticks=[], yticks=[])
plt.show()
More reading
More details about subplot mosaic.
More details about constrained layout, used to align spacing in most of these examples.
https://matplotlib.org/stable/users/explain/axes/arranging_axes.html 10/11
19/04/2024 Arranging multiple Axes in a Figure — Matplotlib 3.8.4 documentation
References
The use of the following functions, methods, classes and modules is shown in this example:
matplotlib.pyplot.subplots
matplotlib.pyplot.subplot_mosaic
matplotlib.figure.Figure.add_gridspec
matplotlib.figure.Figure.add_subplot
matplotlib.gridspec.GridSpec
matplotlib.gridspec.SubplotSpec.subgridspec
matplotlib.gridspec.GridSpecFromSubplotSpec
© Copyright 2002–2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib
development team; 2012–2024 The Matplotlib development team.
Built with the PyData
Created using Sphinx 7.2.6. Sphinx Theme 0.13.3.
https://matplotlib.org/stable/users/explain/axes/arranging_axes.html 11/11