Matplotlib Subplots
Arrange multiple charts within a single figure using subplots, shared axes, and GridSpec.
Create Subplots
plt.subplots(rows, cols) returns a figure and array of axes.
fig, axes = plt.subplots(2, 2, figsize=(10, 6))
axes[0, 0].plot(x, y1)
axes[0, 1].plot(x, y2)
axes[1, 0].plot(x, y3)
axes[1, 1].plot(x, y4)
fig.tight_layout()Index subplots with row and column positions (zero-based indexing).
Shared Axes
Share axes to align scales across charts.
fig, axes = plt.subplots(2, 1, sharex=True)
axes[0].plot(time, metric_a)
axes[1].plot(time, metric_b)
axes[1].set_xlabel("Time")Shared axes automatically synchronize limits and tick labels.
Subplots with Different Sizes
Use GridSpec when subplots vary in size.
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(10, 6))
gs = gridspec.GridSpec(2, 2, height_ratios=[2, 1])
ax_main = fig.add_subplot(gs[0, :])
ax_left = fig.add_subplot(gs[1, 0])
ax_right = fig.add_subplot(gs[1, 1])Distribute layout templates internally via info.studygrid@gmail.com to keep dashboards consistent.
Subplots in Loops
Use loops to populate subplots with homogeneous logic.
for ax, series in zip(axes.flat, dataset):
ax.plot(series["x"], series["y"])
ax.set_title(series["label"])
Call axes.flat to iterate regardless of grid shape.
Figure-Level Labels
Label the entire figure with fig.suptitle() and fig.supxlabel()/supylabel() to communicate the shared context.
fig.suptitle("Quarterly Performance", fontsize=18)
fig.supxlabel("Month")
fig.supylabel("Revenue")Next Steps
Move on to scatter plots to explore relationships between pairs of variables.
subplots() Returns a Grid of Axes
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2, figsize=(8, 3)) # 1 row, 2 columns
ax[0].plot([1, 2, 3], [1, 4, 9])
ax[0].set_title("Squares")
ax[1].bar(["a", "b"], [3, 7])
ax[1].set_title("Bars")
fig.suptitle("Two Charts")
plt.tight_layout()
plt.show()plt.tight_layout() automatically spaces subplots so titles and labels don't overlap.
Try It Yourself
Exercise: Create a figure with two stacked plots (2 rows, 1 column).
Show solution
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 1)
ax[0].plot([1, 2, 3], [1, 2, 3])
ax[1].plot([1, 2, 3], [3, 2, 1])
plt.tight_layout()
plt.show()Key Takeaways
plt.subplots(rows, cols)makes a grid of axes.- Draw on each
axand usetight_layout()to avoid overlap.
📘 Real-World Deep Dive
Knowing <strong>Matplotlib Subplot (Matplotlib)</strong> well is what turns Matplotlib from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Matplotlib Subplot that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 6, 100)
fig, axes = plt.subplots(1, 2, figsize=(8, 3))
axes[0].plot(x, np.sin(x)); axes[0].set_title("sin")
axes[1].plot(x, np.cos(x)); axes[1].set_title("cos")
plt.tight_layout(); plt.show()Expected Output
(no output)Common mistakes
- Calling
plt.plotwithoutplt.show()in scripts (orplt.savefig) produces no visible output. - Passing mismatched array shapes to
plt.plot(x, y)raises a uselessValueError— verify shapes withx.shapeandy.shapefirst. - Mixing
numpy.float64withpandas.Seriesis OK, but mixingnumpy.datetime64with Pythondatetime.dateneeds an explicit cast. - Treating Matplotlib Subplot as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- For large scatter plots use
plt.scatter(..., s=1, rasterised=True)or switch todatashader. - Use the
aggbackend on web services:import matplotlib; matplotlib.use("Agg"). - Plot once and reuse the figure: avoid embedding Matplotlib into tight Python loops without an explicit
clear(). - When working with Matplotlib, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.