How to Create Multiple Subplots in Matplotlib in Python?
0 711
How to Create Multiple Subplots in Matplotlib in Python
When visualizing data in Python using Matplotlib, sometimes one plot isn’t enough. You may want to display several visualizations side by side to compare trends, patterns, or relationships. That’s where multiple subplots come into play. Let’s explore how to generate them efficiently using Matplotlib’s tools.
Understanding Subplots in Matplotlib
A subplot is simply one of many plots contained within a single figure. Matplotlib provides a convenient function called plt.subplots() that helps you create a grid of plots. Each cell in the grid is an individual Axes object where you can draw your graph.
Creating Basic Subplots with plt.subplots()
Let’s begin by creating a simple 2x2 layout of subplots. Each subplot will display a sine wave just for demonstration.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create a 2x2 grid of subplots
fig, axes = plt.subplots(2, 2)
# Loop through each subplot and plot the same data
for row in axes:
for ax in row:
ax.plot(x, y)
ax.set_title("Sine Wave")
plt.tight_layout()
plt.show()
This code generates four small plots within a single window. The function plt.tight_layout() ensures the plots don’t overlap.
Customizing Individual Subplots
You’re not limited to plotting the same thing in each subplot. Each Axes object can be modified independently. Here’s an example with different trigonometric functions:
fig, axes = plt.subplots(2, 2)
axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title("Sine")
axes[0, 1].plot(x, np.cos(x))
axes[0, 1].set_title("Cosine")
axes[1, 0].plot(x, np.tan(x))
axes[1, 0].set_title("Tangent")
axes[1, 1].plot(x, np.exp(-x))
axes[1, 1].set_title("Exponential Decay")
plt.tight_layout()
plt.show()
This example assigns a unique plot to each subplot using the axes array.
Sharing Axes Between Subplots
If your plots share the same scale or range, you can tell Matplotlib to share axes between them. This ensures better visual alignment:
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
for i in range(2):
for j in range(2):
axes[i, j].plot(x, np.sin(x + (i + j)))
axes[i, j].set_title(f"Shifted Sine {i+j}")
plt.tight_layout()
plt.show()
Using sharex=True and sharey=True links the axes, so zooming or panning in one plot applies to the others (when using interactive backends).
One-Dimensional Subplot Grids
If you want a single row or column of subplots, you can simplify the code like this:
# One row, three columns
fig, axes = plt.subplots(1, 3)
titles = ["Sine", "Cosine", "Tangent"]
functions = [np.sin, np.cos, np.tan]
for ax, func, title in zip(axes, functions, titles):
ax.plot(x, func(x))
ax.set_title(title)
plt.tight_layout()
plt.show()
In this format, axes is a 1D array instead of a 2D matrix, making it easier to loop through when you only need a row or column of plots.
Conclusion
Matplotlib’s subplot functionality is a powerful way to present multiple visualizations in a single figure. By adjusting layout, sharing axes, or customizing each Axes individually, you can create clean and informative plots tailored to your analysis needs. Once you get the hang of it, subplots become a go-to tool in your data visualization workflow.
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments