杰瑞科技汇

Python plt.subplots()如何实现多子图布局?

Of course! The term you're likely looking for is plt.subplot(). This is a fundamental function in Matplotlib for creating plots with multiple panels or subplots within a single figure.

Python plt.subplots()如何实现多子图布局?-图1
(图片来源网络,侵删)

Let's break it down.

The Core Concept: plt.subplot()

plt.subplot() is used to create a grid of subplots. You specify the number of rows, the number of columns, and the index of the subplot you want to create or activate.

Syntax: plt.subplot(rows, columns, index)

  • rows: The number of rows in the grid.
  • columns: The number of columns in the grid.
  • index: The position of the subplot. This index starts at 1 and goes from left to right, then top to bottom.

Example 1: Simple 2x2 Grid of Subplots

This is the most common use case. Let's create a 2x2 grid (2 rows, 2 columns).

Python plt.subplots()如何实现多子图布局?-图2
(图片来源网络,侵删)
import matplotlib.pyplot as plt
import numpy as np
# Generate some sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = x**2
y4 = np.exp(x/5)
# --- Create the subplots ---
# 1. Create the first subplot (top-left)
plt.subplot(2, 2, 1)  # 2 rows, 2 columns, position 1
plt.plot(x, y1, 'r-') # 'r-' means red, solid line'Sine Wave')
# 2. Create the second subplot (top-right)
plt.subplot(2, 2, 2)  # 2 rows, 2 columns, position 2
plt.plot(x, y2, 'g--') # 'g--' means green, dashed line'Cosine Wave')
# 3. Create the third subplot (bottom-left)
plt.subplot(2, 2, 3)  # 2 rows, 2 columns, position 3
plt.plot(x, y3, 'b:')  # 'b:' means blue, dotted line'Quadratic')
# 4. Create the fourth subplot (bottom-right)
plt.subplot(2, 2, 4)  # 2 rows, 2 columns, position 4
plt.plot(x, y4, 'm-.') # 'm-.' means magenta, dash-dot line'Exponential')
# Add a main title to the entire figure
plt.suptitle('A 2x2 Grid of Subplots')
# Adjust layout to prevent titles from overlapping
plt.tight_layout()
# Display the plot
plt.show()

Output:


The Modern Object-Oriented Approach (Recommended)

While plt.subplot() works perfectly, the more modern and flexible way to work with Matplotlib is using the object-oriented API. It's less prone to errors, especially when your plots get more complex.

The key is to use plt.subplots() (note the s at the end). This function creates a figure and a set of subplots at once, returning them as objects.

Syntax: fig, axes = plt.subplots(rows, columns)

  • fig: The entire figure object.
  • axes: A NumPy array of subplot objects. You access each subplot using axes[row, column].

Let's rewrite the previous example using this method.

import matplotlib.pyplot as plt
import numpy as np
# Generate some sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = x**2
y4 = np.exp(x/5)
# --- Create the figure and subplots using the OOP approach ---
# fig is the whole figure, axes is an array of the subplots
fig, axes = plt.subplots(2, 2, figsize=(10, 8)) # figsize makes the figure larger
# Now, we plot on each specific 'axes' object
# axes[0, 0] is the top-left subplot
axes[0, 0].plot(x, y1, 'r-')
axes[0, 0].set_title('Sine Wave')
axes[0, 0].set_xlabel('X-axis')
axes[0, 0].set_ylabel('Y-axis')
# axes[0, 1] is the top-right subplot
axes[0, 1].plot(x, y2, 'g--')
axes[0, 1].set_title('Cosine Wave')
# axes[1, 0] is the bottom-left subplot
axes[1, 0].plot(x, y3, 'b:')
axes[1, 0].set_title('Quadratic')
# axes[1, 1] is the bottom-right subplot
axes[1, 1].plot(x, y4, 'm-.')
axes[1, 1].set_title('Exponential')
# Add a main title to the entire figure
fig.suptitle('A 2x2 Grid of Subplots (OOP Method)')
# Adjust layout to prevent titles from overlapping
plt.tight_layout(rect=[0, 0, 1, 0.96]) # rect adjusts the suptitle space
# Display the plot
plt.show()

Why is the OOP method better?

  • Clarity: axes[0, 0].plot() is very explicit about where you are plotting.
  • Flexibility: It's much easier to handle complex layouts, like figures with different sized subplots.
  • Less Stateful: You don't rely on Matplotlib's "current" active plot, which can sometimes lead to unexpected behavior.

Advanced: Subplots of Different Sizes (GridSpec)

Sometimes you don't want a simple grid. You might want one large plot on top and two smaller ones below. For this, GridSpec is the perfect tool.

GridSpec allows you to specify a more complex grid layout.

import matplotlib.pyplot as plt
import numpy as np
# Generate data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.exp(x/5)
# Create a GridSpec layout
# 3 rows, 1 column. The first row should take up 2/3 of the height.
fig = plt.figure(figsize=(8, 10))
gs = fig.add_gridspec(3, 1, height_ratios=[2, 1, 1])
# Create subplots based on the GridSpec
ax1 = fig.add_subplot(gs[0, 0]) # The first (top) subplot
ax2 = fig.add_subplot(gs[1, 0]) # The second (middle) subplot
ax3 = fig.add_subplot(gs[2, 0]) # The third (bottom) subplot
# Plot on each subplot
ax1.plot(x, y1, 'r-')
ax1.set_title('Large Sine Wave Plot')
ax2.plot(x, y2, 'g--')
ax2.set_title('Smaller Cosine Wave Plot')
ax3.plot(x, y3, 'b:')
ax3.set_title('Smaller Exponential Plot')
# Adjust layout
plt.tight_layout()
plt.show()

Output:

Summary: Which one should you use?

Method When to Use Key Command
plt.subplot() Quick and simple plots, simple scripts, interactive use. Good for beginners. plt.subplot(r, c, i)
plt.subplots() Recommended for most cases. Scripts, functions, and any non-trivial plotting. fig, axes = plt.subplots(r, c)
fig.add_gridspec() When you need complex, non-uniform layouts (e.g., one large plot with smaller ones). gs = fig.add_gridspec(...)

For any serious project or reusable code, get into the habit of using the object-oriented approach with plt.subplots(). It will save you headaches in the long run.

分享:
扫描分享到社交APP
上一篇
下一篇