Make subplots span multiple grid rows and columns in Matplotlib

Python

Matplotlib

Figure

Create non-uniform grid

Luc B.

Python

Matplotlib

Creating a uniform grid of plots is easy enough with Matplotlib's subplot API. However, sometimes users need more than a uniform grid. For example, a user may want a figure with two adjacent plots in the top row and a single plot in the bottom row. This is accomplished with Matplotlib's GridSpec API, which expands upon the subplot functionality.

Code Example

Use the Figure.add_gridspec() function to create a GridSpec object, then use Python's array slicing operators to allocate the grid to different subplots.

Using GridSpec requires the use of Matplotlib's object oriented interface instead of the pyplot interface.

import matplotlib.pyplot as plt

fig = plt.figure(constrained_layout=True)

# Create a 2x2 GridSpec grid
spec = fig.add_gridspec(2, 2)

# Modify top-left plot
tl = fig.add_subplot(spec[0, 0])
tl.set_title("Top Left")

# Modify top-right plot
tr = fig.add_subplot(spec[0, 1])
tr.set_title("Top Right")

# Modify bottom plot
b = fig.add_subplot(spec[1, 0:2])
b.set_title("Bottom")

plt.show()

png

Conceptually, the object returned by Figure.add_gridspec() is a 2D array. Slicing up that array and passing it to Figure.add_subplot() allows users to create subplots for any continuous slice of the 2D array.

Note that constrained_layout=True informs Matplotlib to automatically resize subplots so nothing overlaps.