Skip to main content

Matplotlib (Part 3): Subplots and figures

Comparisons often demand multiple linked views: revenue beside costs, residuals under predictions. **Part 2** refined one Axes—now orchestrate grids of them efficiently.


📚 Prerequisites

  • Matplotlib fundamentals from Parts 1–2.

🎯 What you'll master

  • Create regular subplot grids (subplots).
  • Share axes and align labels cleanly across rows/columns.

Simple grids

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(9, 6), sharex=True)

for ax, title in zip(axes.flat, ["A", "B", "C", "D"]):
ax.plot([0, 1, 2], [0, 1, 0])
ax.set_title(f"panel {title}")

fig.suptitle("Batch evaluation")
plt.tight_layout(rect=[0, 0, 1, 0.96])
plt.show()

sharey=True is ideal when stacking histograms comparing identical magnitude ranges.


Complex layouts with GridSpec

from matplotlib.gridspec import GridSpec

fig = plt.figure(figsize=(9, 5))
gs = GridSpec(2, 3, figure=fig)
ax_wide = fig.add_subplot(gs[0, :])
ax_bl = fig.add_subplot(gs[1, 0])
ax_bm = fig.add_subplot(gs[1, 1])
ax_br = fig.add_subplot(gs[1, 2])

ax_wide.set_title("summary")
plt.show()

Use this when dashboards need asymmetry—not every insight fits a tidy 2×2.


Saving vector figures for papers or slides

fig.savefig("report.pdf", bbox_inches="tight")

Prefer vector formats (pdf, svg) when stakeholders zoom deeply.


💡 Key takeaways

  • plt.subplots solves 90% of grid needs; escalate to GridSpec selectively.
  • tight_layout + rect reserves space for suptitles so nothing clips.

➡️ Next steps

Let Seaborn pick smarter statistical defaults starting with Seaborn (Part 1): Introduction.