A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://matplotlib.org/stable/api/../users/explain/axes/constrainedlayout_guide.html below:

Constrained layout guide — Matplotlib 3.10.3 documentation

Constrained layout guide#

Use constrained layout to fit plots within your figure cleanly.

Constrained layout automatically adjusts subplots so that decorations like tick labels, legends, and colorbars do not overlap, while still preserving the logical layout requested by the user.

Constrained layout is similar to Tight layout, but is substantially more flexible. It handles colorbars placed on multiple Axes (Placing colorbars) nested layouts (subfigures) and Axes that span rows or columns (subplot_mosaic), striving to align spines from Axes in the same row or column. In addition, Compressed layout will try and move fixed aspect-ratio Axes closer together. These features are described in this document, as well as some implementation details discussed at the end.

Constrained layout typically needs to be activated before any Axes are added to a figure. Two ways of doing so are

Those are described in detail throughout the following sections.

Warning

Calling tight_layout will turn off constrained layout!

Simple example#

With the default Axes positioning, the axes title, axis labels, or tick labels can sometimes go outside the figure area, and thus get clipped.

To prevent this, the location of Axes needs to be adjusted. For subplots, this can be done manually by adjusting the subplot parameters using Figure.subplots_adjust. However, specifying your figure with the layout="constrained" keyword argument will do the adjusting automatically.

When you have multiple subplots, often you see labels of different Axes overlapping each other.

Specifying layout="constrained" in the call to plt.subplots causes the layout to be properly constrained.

Colorbars#

If you create a colorbar with Figure.colorbar, you need to make room for it. Constrained layout does this automatically. Note that if you specify use_gridspec=True it will be ignored because this option is made for improving the layout via tight_layout.

Note

For the pcolormesh keyword arguments (pc_kwargs) we use a dictionary to keep the calls consistent across this document.

arr = np.arange(100).reshape((10, 10))
norm = mcolors.Normalize(vmin=0., vmax=100.)
# see note above: this makes all pcolormesh calls consistent:
pc_kwargs = {'rasterized': True, 'cmap': 'viridis', 'norm': norm}
fig, ax = plt.subplots(figsize=(4, 4), layout="constrained")
im = ax.pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=ax, shrink=0.6)

If you specify a list of Axes (or other iterable container) to the ax argument of colorbar, constrained layout will take space from the specified Axes.

If you specify a list of Axes from inside a grid of Axes, the colorbar will steal space appropriately, and leave a gap, but all subplots will still be the same size.

fig, axs = plt.subplots(3, 3, figsize=(4, 4), layout="constrained")
for ax in axs.flat:
    im = ax.pcolormesh(arr, **pc_kwargs)
fig.colorbar(im, ax=axs[1:, 1], shrink=0.8)
fig.colorbar(im, ax=axs[:, -1], shrink=0.6)
Suptitle#

Constrained layout can also make room for suptitle.

Padding and spacing#

Padding between Axes is controlled in the horizontal by w_pad and wspace, and vertical by h_pad and hspace. These can be edited via set. w/h_pad are the minimum space around the Axes in units of inches:

Spacing between subplots is further set by wspace and hspace. These are specified as a fraction of the size of the subplot group as a whole. If these values are smaller than w_pad or h_pad, then the fixed pads are used instead. Note in the below how the space at the edges doesn't change from the above, but the space between subplots does.

If there are more than two columns, the wspace is shared between them, so here the wspace is divided in two, with a wspace of 0.1 between each column:

GridSpecs also have optional hspace and wspace keyword arguments, that will be used instead of the pads set by constrained layout:

fig, axs = plt.subplots(2, 2, layout="constrained",
                        gridspec_kw={'wspace': 0.3, 'hspace': 0.2})
for ax in axs.flat:
    example_plot(ax, hide_labels=True)
# this has no effect because the space set in the gridspec trumps the
# space set in *constrained layout*.
fig.get_layout_engine().set(w_pad=4 / 72, h_pad=4 / 72, hspace=0.0,
                            wspace=0.0)
Spacing with colorbars#

Colorbars are placed a distance pad from their parent, where pad is a fraction of the width of the parent(s). The spacing to the next subplot is then given by w/hspace.

fig, axs = plt.subplots(2, 2, layout="constrained")
pads = [0, 0.05, 0.1, 0.2]
for pad, ax in zip(pads, axs.flat):
    pc = ax.pcolormesh(arr, **pc_kwargs)
    fig.colorbar(pc, ax=ax, shrink=0.6, pad=pad)
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.set_title(f'pad: {pad}')
fig.get_layout_engine().set(w_pad=2 / 72, h_pad=2 / 72, hspace=0.2,
                            wspace=0.2)
rcParams#

There are five rcParams that can be set, either in a script or in the matplotlibrc file. They all have the prefix figure.constrained_layout:

Use with GridSpec#

Constrained layout is meant to be used with subplots(), subplot_mosaic(), or GridSpec() with add_subplot().

Note that in what follows layout="constrained"

More complicated gridspec layouts are possible. Note here we use the convenience functions add_gridspec and subgridspec.

Note that in the above the left and right columns don't have the same vertical extent. If we want the top and bottom of the two grids to line up then they need to be in the same gridspec. We need to make this figure larger as well in order for the Axes not to collapse to zero height:

fig = plt.figure(figsize=(4, 6), layout="constrained")

gs0 = fig.add_gridspec(6, 2)

ax1 = fig.add_subplot(gs0[:3, 0])
ax2 = fig.add_subplot(gs0[3:, 0])

example_plot(ax1)
example_plot(ax2)

ax = fig.add_subplot(gs0[0:2, 1])
example_plot(ax, hide_labels=True)
ax = fig.add_subplot(gs0[2:4, 1])
example_plot(ax, hide_labels=True)
ax = fig.add_subplot(gs0[4:, 1])
example_plot(ax, hide_labels=True)
fig.suptitle('Overlapping Gridspecs')

This example uses two gridspecs to have the colorbar only pertain to one set of pcolors. Note how the left column is wider than the two right-hand columns because of this. Of course, if you wanted the subplots to be the same size you only needed one gridspec. Note that the same effect can be achieved using subfigures.

Rather than using subgridspecs, Matplotlib now provides subfigures which also work with constrained layout:

Manually setting Axes positions#

There can be good reasons to manually set an Axes position. A manual call to set_position will set the Axes so constrained layout has no effect on it anymore. (Note that constrained layout still leaves the space for the Axes that is moved).

fig, axs = plt.subplots(1, 2, layout="constrained")
example_plot(axs[0], fontsize=12)
axs[1].set_position([0.2, 0.2, 0.4, 0.4])
Grids of fixed aspect-ratio Axes: "compressed" layout#

Constrained layout operates on the grid of "original" positions for Axes. However, when Axes have fixed aspect ratios, one side is usually made shorter, and leaves large gaps in the shortened direction. In the following, the Axes are square, but the figure quite wide so there is a horizontal gap:

One obvious way of fixing this is to make the figure size more square, however, closing the gaps exactly requires trial and error. For simple grids of Axes we can use layout="compressed" to do the job for us:

Manually turning off constrained layout#

Constrained layout usually adjusts the Axes positions on each draw of the figure. If you want to get the spacing provided by constrained layout but not have it update, then do the initial draw and then call fig.set_layout_engine('none'). This is potentially useful for animations where the tick labels may change length.

Note that constrained layout is turned off for ZOOM and PAN GUI events for the backends that use the toolbar. This prevents the Axes from changing position during zooming and panning.

Limitations# Incompatible functions#

Constrained layout will work with pyplot.subplot, but only if the number of rows and columns is the same for each call. The reason is that each call to pyplot.subplot will create a new GridSpec instance if the geometry is not the same, and constrained layout. So the following works fine:

but the following leads to a poor layout:

Similarly, subplot2grid works with the same limitation that nrows and ncols cannot change for the layout to look good.

fig = plt.figure(layout="constrained")

ax1 = plt.subplot2grid((3, 3), (0, 0))
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)

example_plot(ax1)
example_plot(ax2)
example_plot(ax3)
example_plot(ax4)
fig.suptitle('subplot2grid')
Other caveats# Debugging#

Constrained layout can fail in somewhat unexpected ways. Because it uses a constraint solver the solver can find solutions that are mathematically correct, but that aren't at all what the user wants. The usual failure mode is for all sizes to collapse to their smallest allowable value. If this happens, it is for one of two reasons:

  1. There was not enough room for the elements you were requesting to draw.

  2. There is a bug - in which case open an issue at matplotlib/matplotlib#issues.

If there is a bug, please report with a self-contained example that does not require outside data or dependencies (other than numpy).

Notes on the algorithm#

The algorithm for the constraint is relatively straightforward, but has some complexity due to the complex ways we can lay out a figure.

Layout in Matplotlib is carried out with gridspecs via the GridSpec class. A gridspec is a logical division of the figure into rows and columns, with the relative width of the Axes in those rows and columns set by width_ratios and height_ratios.

In constrained layout, each gridspec gets a layoutgrid associated with it. The layoutgrid has a series of left and right variables for each column, and bottom and top variables for each row, and further it has a margin for each of left, right, bottom and top. In each row, the bottom/top margins are widened until all the decorators in that row are accommodated. Similarly, for columns and the left/right margins.

Simple case: one Axes#

For a single Axes the layout is straight forward. There is one parent layoutgrid for the figure consisting of one column and row, and a child layoutgrid for the gridspec that contains the Axes, again consisting of one row and column. Space is made for the "decorations" on each side of the Axes. In the code, this is accomplished by the entries in do_constrained_layout() like:

gridspec._layoutgrid[0, 0].edit_margin_min('left',
      -bbox.x0 + pos.x0 + w_pad)

where bbox is the tight bounding box of the Axes, and pos its position. Note how the four margins encompass the Axes decorations.

from matplotlib._layoutgrid import plot_children

fig, ax = plt.subplots(layout="constrained")
example_plot(ax, fontsize=24)
plot_children(fig)
Simple case: two Axes#

When there are multiple Axes they have their layouts bound in simple ways. In this example the left Axes has much larger decorations than the right, but they share a bottom margin, which is made large enough to accommodate the larger xlabel. Same with the shared top margin. The left and right margins are not shared, and hence are allowed to be different.

fig, ax = plt.subplots(1, 2, layout="constrained")
example_plot(ax[0], fontsize=32)
example_plot(ax[1], fontsize=8)
plot_children(fig)
Two Axes and colorbar#

A colorbar is simply another item that expands the margin of the parent layoutgrid cell:

Colorbar associated with a Gridspec#

If a colorbar belongs to more than one cell of the grid, then it makes a larger margin for each:

Uneven sized Axes#

There are two ways to make Axes have an uneven size in a Gridspec layout, either by specifying them to cross Gridspecs rows or columns, or by specifying width and height ratios.

The first method is used here. Note that the middle top and bottom margins are not affected by the left-hand column. This is a conscious decision of the algorithm, and leads to the case where the two right-hand Axes have the same height, but it is not 1/2 the height of the left-hand Axes. This is consistent with how gridspec works without constrained layout.

One case that requires finessing is if margins do not have any artists constraining their width. In the case below, the right margin for column 0 and the left margin for column 3 have no margin artists to set their width, so we take the maximum width of the margin widths that do have artists. This makes all the Axes have the same size:

Total running time of the script: (0 minutes 22.366 seconds)

Gallery generated by Sphinx-Gallery


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4