Matplotlib Subplots

Create multiple plots in a single figure for better data comparison

📊 Multiple Plots

Subplots allow you to display multiple charts in one figure, making it easy to compare different datasets or show related information side by side.


import matplotlib.pyplot as plt

# Create 2x2 subplots
fig, axes = plt.subplots(2, 2)

# Plot in each subplot
axes[0, 0].plot([1, 2, 3], [1, 4, 2])
axes[0, 1].plot([1, 2, 3], [2, 3, 1])

plt.show()
                                    
Grid
Layout
Flexible
Sizing
Easy
Comparison

Subplot Creation Methods

Different ways to create and organize multiple plots:

⊞

plt.subplot()

Simple subplot creation

Basic Sequential
⊟

plt.subplots()

Create all subplots at once

Grid Array Access
⊡

GridSpec

Advanced layout control

Custom Complex
🎯

Figure Size

Control overall dimensions

figsize Spacing

🔹 Basic Subplots

Create simple subplot arrangements

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4]
y1 = [1, 4, 2, 3]
y2 = [2, 3, 1, 4]

# Method 1: Using plt.subplot()
plt.figure(figsize=(10, 4))

plt.subplot(1, 2, 1)  # 1 row, 2 columns, 1st subplot
plt.plot(x, y1, 'ro-')
plt.title('First Plot')

plt.subplot(1, 2, 2)  # 1 row, 2 columns, 2nd subplot
plt.plot(x, y2, 'bo-')
plt.title('Second Plot')

plt.tight_layout()  # Adjust spacing
plt.show()

# Method 2: Using plt.subplots()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))

ax1.plot(x, y1, 'go-')
ax1.set_title('Left Plot')

ax2.plot(x, y2, 'mo-')
ax2.set_title('Right Plot')

plt.tight_layout()
plt.show()

🔹 Grid Layouts

Create 2D grids of subplots

import matplotlib.pyplot as plt
import numpy as np

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

# Sample data
x = np.linspace(0, 10, 100)

# Plot in each subplot
axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title('sin(x)')

axes[0, 1].plot(x, np.cos(x), 'r')
axes[0, 1].set_title('cos(x)')

axes[1, 0].plot(x, np.tan(x), 'g')
axes[1, 0].set_title('tan(x)')
axes[1, 0].set_ylim(-2, 2)  # Limit y-axis for tan

axes[1, 1].plot(x, x**2, 'm')
axes[1, 1].set_title('x²')

# Add overall title
fig.suptitle('Mathematical Functions', fontsize=16)

plt.tight_layout()
plt.show()

# Alternative: Loop through subplots
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
functions = [np.sin, np.cos, np.tan, lambda x: x**2]
titles = ['sin(x)', 'cos(x)', 'tan(x)', 'x²']
colors = ['b', 'r', 'g', 'm']

for i, ax in enumerate(axes.flat):
    ax.plot(x, functions[i](x), colors[i])
    ax.set_title(titles[i])
    if i == 2:  # tan function
        ax.set_ylim(-2, 2)

plt.tight_layout()
plt.show()

🔹 Sharing Axes

Share x or y axes between subplots

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 50)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x) * np.cos(x)

# Share x-axis
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(8, 10), sharex=True)

ax1.plot(x, y1, 'b-')
ax1.set_title('sin(x)')
ax1.grid(True)

ax2.plot(x, y2, 'r-')
ax2.set_title('cos(x)')
ax2.grid(True)

ax3.plot(x, y3, 'g-')
ax3.set_title('sin(x) × cos(x)')
ax3.set_xlabel('x values')
ax3.grid(True)

plt.tight_layout()
plt.show()

# Share y-axis
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), sharey=True)

ax1.plot(x, y1, 'b-')
ax1.set_title('sin(x)')
ax1.set_ylabel('y values')

ax2.plot(x, y2, 'r-')
ax2.set_title('cos(x)')

plt.tight_layout()
plt.show()

🔹 Different Plot Types

Combine different chart types in subplots

import matplotlib.pyplot as plt
import numpy as np

# Sample data
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]
x = np.linspace(0, 10, 50)
y = np.sin(x)

# Create subplots with different chart types
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 10))

# Line plot
ax1.plot(x, y, 'b-', linewidth=2)
ax1.set_title('Line Plot')
ax1.grid(True)

# Bar chart
ax2.bar(categories, values, color='skyblue')
ax2.set_title('Bar Chart')

# Scatter plot
np.random.seed(42)
x_scatter = np.random.randn(50)
y_scatter = np.random.randn(50)
ax3.scatter(x_scatter, y_scatter, alpha=0.6, color='red')
ax3.set_title('Scatter Plot')

# Histogram
data = np.random.normal(0, 1, 1000)
ax4.hist(data, bins=30, alpha=0.7, color='green')
ax4.set_title('Histogram')

plt.tight_layout()
plt.show()

🔹 Subplot Spacing and Layout

Control spacing and arrangement of subplots

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 50)

# Custom spacing with subplots_adjust
fig, axes = plt.subplots(2, 2, figsize=(10, 8))

axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title('Plot 1')

axes[0, 1].plot(x, np.cos(x))
axes[0, 1].set_title('Plot 2')

axes[1, 0].plot(x, np.tan(x))
axes[1, 0].set_title('Plot 3')
axes[1, 0].set_ylim(-2, 2)

axes[1, 1].plot(x, x**0.5)
axes[1, 1].set_title('Plot 4')

# Adjust spacing manually
plt.subplots_adjust(
    left=0.1,     # Left margin
    bottom=0.1,   # Bottom margin
    right=0.9,    # Right margin
    top=0.9,      # Top margin
    wspace=0.4,   # Width spacing between subplots
    hspace=0.4    # Height spacing between subplots
)

plt.show()

# Using tight_layout for automatic spacing
fig, axes = plt.subplots(2, 3, figsize=(15, 8))

for i, ax in enumerate(axes.flat):
    ax.plot(x, np.sin(x + i))
    ax.set_title(f'Subplot {i+1}')
    ax.grid(True, alpha=0.3)

plt.tight_layout(pad=2.0)  # Add padding
plt.show()

🧠 Test Your Knowledge

What does plt.subplot(2, 3, 4) create?

Which parameter in plt.subplots() shares the x-axis?