Lecture

Multiple Subplots and Figures

Up to now, you’ve worked with one chart per figure. But what if you want to compare several plots side by side?

Matplotlib lets you organize multiple plots within a single figure using subplots, or create entirely separate figures for different visualizations.


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 control the layout by setting the number of rows and columns, while the index determines each subplot’s position in the grid.


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 you want to compare related datasets in a single visual space.
  • Use multiple figures when creating distinct visualizations for separate analyses or outputs.
Quiz
0 / 1

How can you create multiple plots within a single figure using Matplotlib?

In Matplotlib, use `plt.subplot( , cols, index)` to create multiple plots within a single figure.
rows
columns
figures
axes

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help