SwadhyAI Notes

All Python notes

Matplotlib Subplot 🖼️

Multiple Plots

The subplot() function allows you to draw multiple plots in a single figure.

✨ The subplot() Function

It takes three arguments: rows, columns, and index.

python
import matplotlib.pyplot as plt
import numpy as np

# Plot 1
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1) # 1 row, 2 cols, index 1
plt.plot(x,y)
plt.title("SALES")

# Plot 2
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(1, 2, 2) # 1 row, 2 cols, index 2
plt.plot(x,y)
plt.title("INCOME")

plt.suptitle("MY SHOP") # Super title for the whole figure
plt.show()

✨ Pro Tip: plt.subplots()

For more complex layouts, the plt.subplots() function is often easier to use as it returns a figure and an array of axes.

python
fig, axs = plt.subplots(2, 2) # 2x2 grid
axs[0, 0].plot(x, y)
axs[0, 1].plot(x, y)
# ...