Complex and semantic figure composition (subplot_mosaic)
Laying out Axes in a Figure in a non-uniform grid can be both tedious
and verbose. For dense, even grids we have Figure.subplots but for
more complex layouts, such as Axes that span multiple columns / rows
of the layout or leave some areas of the Figure blank, you can use
gridspec.GridSpec (see Arranging multiple Axes in a Figure) or
manually place your Axes. Figure.subplot_mosaic aims to provide an
interface to visually lay out your Axes (as either ASCII art or nested
lists) to streamline this process.
This interface naturally supports naming your Axes.
Figure.subplot_mosaic returns a dictionary keyed on the
labels used to lay out the Figure. By returning data structures with
names, it is easier to write plotting code that is independent of the
Figure layout.
This is inspired by a proposed MEP and the
patchwork library for R.
While we do not implement the operator overloading style, we do
provide a Pythonic API for specifying (nested) Axes layouts.
importmatplotlib.pyplotaspltimportnumpyasnp# Helper function used for visualization in the following examplesdefidentify_axes(ax_dict,fontsize=48):""" Helper to identify the Axes in the examples below. Draws the label in a large font in the center of the Axes. Parameters ---------- ax_dict : dict[str, Axes] Mapping between the title / label and the Axes. fontsize : int, optional How big the label should be. """kw=dict(ha="center",va="center",fontsize=fontsize,color="darkgrey")fork,axinax_dict.items():ax.text(0.5,0.5,k,transform=ax.transAxes,**kw)
If we want a 2x2 grid we can use Figure.subplots which returns a 2D array
of axes.Axes which we can index into to do our plotting.
A key difference between Figure.subplots and
Figure.subplot_mosaic is the return value. While the former
returns an array for index access, the latter returns a dictionary
mapping the labels to the axes.Axes instances created
will give us 4 Axes laid out in a 2x2 grid and generates the same
figure mosaic as above (but now labeled with {"A","B","C","D"} rather than {"bar","plot","hist","image"}).
Something we can do with Figure.subplot_mosaic, that we cannot
do with Figure.subplots, is to specify that an Axes should span
several rows or columns.
If we want to re-arrange our four Axes to have "C" be a horizontal
span on the bottom and "D" be a vertical span on the right we would do
axd=plt.figure(layout="constrained").subplot_mosaic(""" ABD CCD """)identify_axes(axd)
If we do not want to fill in all the spaces in the Figure with Axes,
we can specify some spaces in the grid to be blank
It is not recommended to use white space as either a label or an
empty sentinel with the string shorthand because it may be stripped
while processing the input.
In this case we want to use the input to specify the arrangement,
but set the relative widths of the rows / columns. For convenience,
gridspec.GridSpec's height_ratios and width_ratios are exposed in the
Figure.subplot_mosaic calling sequence.
axd=plt.figure(layout="constrained").subplot_mosaic(""" .a. bAc .d. """,# set the height ratios between the rowsheight_ratios=[1,3.5,1],# set the width ratios between the columns
Other gridspec.GridSpec keywords can be passed via gridspec_kw. For
example, use the {left, right, bottom, top} keyword arguments to
position the overall mosaic to put multiple versions of the same
mosaic in a figure.
If you need to control the parameters passed to each subplot individually use
per_subplot_kw to pass a mapping between the Axes identifiers (or
tuples of Axes identifiers) to dictionaries of keywords to be passed.
Everything we can do with the string shorthand we can also do when
passing in a list (internally we convert the string shorthand to a nested
list), for example using spans, blanks, and gridspec_kw:
Figure.subplot_mosaic supports sharex and sharey as does
Figure.subplots. When True, all Axes in the mosaic share
the same x-axis or y-axis, which is useful for directly comparing
data across panels.
Note that when using sharex=True only the bottom row of Axes shows
x-axis tick labels, and when using sharey=True only the left column
shows y-axis tick labels. This is identical to the behavior of
Figure.subplots.
Interaction with empty sentinels
When the mosaic layout has blank spaces (empty sentinels), axis sharing
can produce inintended results. In the following example, there are no
tick labels in the top row:
If the layout is specified with the string short-hand, then we know the
Axes labels will be one character and can unambiguously interpret longer
strings in per_subplot_kw to specify a set of Axes to apply the
keywords to: