Course contentsShow
← Data Science
Lesson 1274 of 2,14532. Visualization with Matplotlib and SeabornFree lesson

Creating Multiple Subplots with plt.subplots()

Learn to create figure and axes arrays using plt.subplots() to organize multiple plots in a grid layout.

Creating Multiple Subplots with plt.subplots()

What you'll learn: How to organize multiple visualizations side-by-side in a grid using plt.subplots().

Why Multiple Subplots Matter

When exploring data or presenting findings, you often need to compare multiple visualizations simultaneously. Rather than creating separate figures that require switching between windows, you can arrange them in a grid layout within a single figure—like organizing photos in a photo album grid instead of flipping through loose prints.

The Core Idea

plt.subplots() creates both a figure container and an array of axes (individual plot areas) in one step. Think of it as setting up a blank canvas divided into organized sections, where each section can hold a different chart.

The function returns two objects:

  • fig: The overall figure container
  • axes: An array of axes objects representing each subplot position

Basic Usage

import matplotlib.pyplot as plt

# Create a 2x2 grid of subplots
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))

# Access individual subplots
axes[0, 0].plot([1, 2, 3], [1, 4, 9])  # Top-left
axes[0, 1].scatter([1, 2, 3], [2, 3, 1])  # Top-right
axes[1, 0].bar(['A', 'B', 'C'], [10, 20, 15])  # Bottom-left
axes[1, 1].hist([1, 2, 2, 3, 3, 3, 4], bins=4)  # Bottom-right

plt.tight_layout()  # Prevents overlapping labels
plt.show()

For a single row or column, axes becomes a 1D array:

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4))
axes[0].plot([1, 2, 3])
axes[1].scatter([1, 2, 3], [2, 3, 1])
axes[2].bar(['X', 'Y'], [5, 10])

Key Takeaway: plt.subplots() creates a figure and grid of axes in one call, giving you organized control over multiple plots through array indexing—essential for comparative analysis and dashboard-style presentations.