0
0
Matplotlibdata~5 mins

Nested subplots with subfigures in Matplotlib

Choose your learning style9 modes available
Introduction

Nested subplots with subfigures help you organize multiple plots clearly in one figure. This makes it easier to compare related charts side by side.

You want to show different groups of charts in one figure, each group having its own layout.
You need to compare multiple sets of data with separate titles and labels.
You want to save space by combining many plots in a neat, structured way.
You are preparing a report or presentation and want clear visual sections.
You want to control spacing and arrangement of plots inside bigger plot areas.
Syntax
Matplotlib
fig = plt.figure()
subfigs = fig.subfigures(nrows, ncols)
ax = subfigs[row, col].subplots(nrows, ncols)

fig.subfigures() creates big sections inside the main figure.

Each subfigure can have its own subplots() grid inside it.

Examples
Creates one figure with two side-by-side subfigures, each with one plot.
Matplotlib
fig = plt.figure()
subfigs = fig.subfigures(1, 2)
ax1 = subfigs[0].subplots()
ax2 = subfigs[1].subplots()
Creates two stacked subfigures. The first has two rows of plots, the second has two columns.
Matplotlib
fig = plt.figure()
subfigs = fig.subfigures(2, 1)
ax1 = subfigs[0].subplots(2, 1)
ax2 = subfigs[1].subplots(1, 2)
Sample Program

This code creates a figure with two subfigures side by side. The left subfigure has two line plots stacked vertically. The right subfigure has two scatter plots arranged horizontally. Each subfigure has its own title.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Create main figure
fig = plt.figure(constrained_layout=True, figsize=(8, 6))

# Create 2 subfigures side by side
subfigs = fig.subfigures(1, 2, wspace=0.07)

# Left subfigure with 2 rows of plots
x = np.linspace(0, 10, 100)
ax_left = subfigs[0].subplots(2, 1)
ax_left[0].plot(x, np.sin(x))
ax_left[0].set_title('Sine Wave')
ax_left[1].plot(x, np.cos(x), 'r')
ax_left[1].set_title('Cosine Wave')

# Right subfigure with 2 columns of plots
ax_right = subfigs[1].subplots(1, 2)
ax_right[0].scatter(x, np.sin(x))
ax_right[0].set_title('Sine Scatter')
ax_right[1].scatter(x, np.cos(x), color='orange')
ax_right[1].set_title('Cosine Scatter')

# Set main titles for subfigures
subfigs[0].suptitle('Trigonometric Line Plots')
subfigs[1].suptitle('Trigonometric Scatter Plots')

plt.show()
OutputSuccess
Important Notes

Use constrained_layout=True in plt.figure() to avoid overlapping labels.

Subfigures help keep related plots grouped and easier to read.

You can customize spacing between subfigures with wspace and hspace.

Summary

Nested subplots with subfigures organize multiple plots clearly inside one figure.

Use fig.subfigures() to create big sections, then add subplots inside each.

This method improves readability and layout control for complex visualizations.