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
Line Plot
Plot lines with markers, colors, and styles.
Bar Chart
Draw vertical, horizontal, and grouped bars.
Scatter Plot
Visualize relationships with size and color encodings.
Labels and Legend
Annotate plots with text, arrows, and legend options.
Styles and Themes
Apply built-in styles and customize rcParams.
Save Figure
Export figures to PNG, PDF, and SVG with DPI control.