Nested subplots with subfigures help you organize multiple plots clearly in one figure. This makes it easier to compare related charts side by side.
Nested subplots with subfigures in 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.
fig = plt.figure() subfigs = fig.subfigures(1, 2) ax1 = subfigs[0].subplots() ax2 = subfigs[1].subplots()
fig = plt.figure() subfigs = fig.subfigures(2, 1) ax1 = subfigs[0].subplots(2, 1) ax2 = subfigs[1].subplots(1, 2)
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.
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()
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.
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.