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.
Lessons in this chapter · Visual Storytelling using Matplotlib
- 1. Introduction to Matplotlib for Data Visualization
- 2. Plotting with plt.plot()
- 3. Customizing Lines and Markers
- 4. Adding Titles, Labels, and Legends
- 5. Creating Bar and Pie Charts
- 6. Anatomy of a Matplotlib Plot
- 7. Multiple-choice quiz
- 8. Multiple Subplots and Figures
- 9. Saving Plots to File
- 10. Styling and Themes
- 11. Fill-in-the-blank quiz
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