Skip to main content
Practice

Multiple Subplots and Figures

So far, you've created one chart per figure. But what if you want to compare multiple plots side-by-side?

Matplotlib allows you to display multiple plots within the same figure using subplots.

You can also manage multiple figures in one script.


Subplots: Multiple Plots in One Figure

Use plt.subplot(rows, cols, index) to divide the figure into a grid.

Simple Subplot Example
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y1 = [2, 4, 1, 3]
y2 = [3, 1, 5, 2]

plt.subplot(1, 2, 1) # 1 row, 2 columns, 1st plot
plt.plot(x, y1)
plt.title("Plot A")

plt.subplot(1, 2, 2) # 1 row, 2 columns, 2nd plot
plt.plot(x, y2)
plt.title("Plot B")

plt.tight_layout()
plt.show()

You can control how many rows and columns of plots appear, and the index selects the position.


Managing Multiple Figures

Use plt.figure() to start a new figure. Each figure is independent.

Creating Two Separate Figures
plt.figure(1)
plt.plot([1, 2, 3], [4, 5, 6])
plt.title("Figure 1")

plt.figure(2)
plt.plot([1, 2, 3], [6, 5, 4])
plt.title("Figure 2")

plt.show()

This is useful when generating different types of charts within the same script.


When to Use Each

  • Use subplots when comparing related data on the same page
  • Use multiple figures when making different visualizations for different contexts

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.