Skip to content
Matplotlib

Subplots

Arrange multiple axes with subplots and GridSpec.

By EZ4Code Team
subplotslayout

Code

import matplotlib.pyplot as plt
import numpy as np

# Simple grid
fig, axes = plt.subplots(2, 2, figsize=(8, 6), sharex=True, sharey=True)
x = np.linspace(0, 1, 50)
for ax, k in zip(axes.flat, [1, 2, 3, 4]):
    ax.plot(x, x ** k, label=f"x^{k}")
    ax.legend(loc="upper left")
fig.suptitle("Power functions")
plt.tight_layout()
plt.show()

# Unequal sizes with GridSpec
fig = plt.figure(figsize=(8, 4))
gs = fig.add_gridspec(2, 2, width_ratios=[2, 1])
ax1 = fig.add_subplot(gs[:, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, 1])
plt.show()

Explanation

subplots() returns a Figure and an array of Axes, with sharex and sharey aligning tick labels across panels. Looping over axes.flat lets you fill a grid uniformly. GridSpec enables columns or rows of unequal width when one panel needs more space than the others.

More Matplotlib Snippets