Creating subplots is a crucial skill in data visualization, allowing you to present multiple plots within a single figure. This capability can be particularly beneficial when you need to compare datasets side by side or showcase different aspects of a dataset in a unified and coherent manner. In this section, we'll explore how to create subplots using Matplotlib, a versatile library that offers powerful tools for customizing plot layouts.
In Matplotlib, a figure can contain multiple axes, each representing a subplot. Think of a figure as a canvas and axes as individual plots on that canvas. By arranging multiple axes on a single figure, you can efficiently display and compare various datasets or views of your data.
To create subplots in Matplotlib, you'll use the plt.subplots()
function, which simplifies the process of setting up a grid of plots. This function returns a tuple containing a figure and an array of axes objects, which you can then manipulate individually.
Let's start by creating a simple 2x2 grid of subplots. Each subplot will display a different type of plot for demonstration purposes.
import matplotlib.pyplot as plt
import numpy as np
# Creating some sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = np.exp(x)
# Setting up the 2x2 grid of subplots
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
# Plotting on each subplot
axs[0, 0].plot(x, y1, 'r')
axs[0, 0].set_title('Sine Wave')
axs[0, 1].plot(x, y2, 'g')
axs[0, 1].set_title('Cosine Wave')
axs[1, 0].plot(x, y3, 'b')
axs[1, 0].set_title('Tangent Wave')
axs[1, 1].plot(x, y4, 'y')
axs[1, 1].set_title('Exponential')
# Adjust layout for better spacing
plt.tight_layout()
plt.show()
You can customize the layout of your subplots in several ways:
plt.tight_layout()
or plt.subplots_adjust()
to control the spacing between subplots.gridspec
.Here's an example with shared axes:
# Create subplots with shared axes
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
# Plot data
ax1.plot(x, y1, 'b-', label='Sine')
ax2.plot(x, y2, 'r-', label='Cosine')
# Add labels
ax1.set_title('Trigonometric Functions with Shared X-Axis')
ax1.legend()
ax2.legend()
ax2.set_xlabel('X-axis')
plt.tight_layout()
plt.show()
For more complex layouts, you can use GridSpec
to create custom grid arrangements:
import matplotlib.gridspec as gridspec
# Create figure with complex layout
fig = plt.figure(figsize=(12, 8))
gs = gridspec.GridSpec(2, 3)
# Create subplots of different sizes
ax1 = fig.add_subplot(gs[0, :2])
ax2 = fig.add_subplot(gs[0, 2])
ax3 = fig.add_subplot(gs[1, :])
plt.tight_layout()
plt.show()
This allows you to create more sophisticated layouts where some subplots span multiple grid cells.
Remember that effective use of subplots can greatly enhance the clarity and impact of your visualizations by allowing viewers to compare different aspects of your data in a single view.
© 2025 ApX Machine Learning