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.

import matplotlib.pyplot as plt
import numpy as np

import matplotlib.colors as mcolors
import matplotlib.gridspec as gridspec

plt.rcParams['savefig.facecolor'] = "0.8"
plt.rcParams['figure.figsize'] = 4.5, 4.
plt.rcParams['figure.max_open_warning'] = 50


def example_plot(ax, fontsize=12, hide_labels=False):
    ax.plot([1, 2])

    ax.locator_params(nbins=3)
    if hide_labels:
        ax.set_xticklabels([])
        ax.set_yticklabels([])
    else:
        ax.set_xlabel('x-label', fontsize=fontsize)
        ax.set_ylabel('y-label', fontsize=fontsize)
        ax.set_title('Title', fontsize=fontsize)

fig, ax = plt.subplots(layout=None)
example_plot(ax, fontsize=24)