Matplotlib subplots() Function


Matplotlib 参考文档Matplotlib Reference Documentation

subplots()It is the recommended way to create a Figure and a set of Axes subplots, completing the creation of the canvas and subplots with a single call.

It is the core entry function of Matplotlib's object-oriented interface.

Function Definition

pyplot Interface

matplotlib.pyplot.subplots(nrows=1, ncols=1, *, sharex=False,
    sharey=False, squeeze=True, width_ratios=None,
    height_ratios=None, subplot_kw=None, gridspec_kw=None,
    **fig_kw)

Figure Method

Figure.subplots(nrows=1, ncols=1, *, sharex=False, sharey=False,
    squeeze=True, width_ratios=None, height_ratios=None,
    subplot_kw=None, gridspec_kw=None)

Parameter Description

ParameterTypeDescription
nrowsintNumber of subplot rows, default 1
ncolsintNumber of subplot columns, default 1
sharex / shareybool or strWhether to share x/y axes. Can pass 'all'/'row'/'col'/'none' or boolean values
squeezeboolIf True, automatically removes extra dimensions for single row/column, default True
width_ratioslistWidth ratio of each column, e.g., [1, 2] means column 2 is 2 times wider than column 1
height_ratioslistHeight ratio of each row, e.g., [2, 1] means row 1 is 2 times taller than row 2
subplot_kwdictParameters passed to subplot creation, e.g., dict(projection='polar') to create a polar subplot
gridspec_kwdictParameters passed to GridSpec, e.g., dict(hspace=0.3, wspace=0.3) to set subplot spacing
**fig_kwdictParameters passed to Figure creation, e.g., figsize=(8,6), dpi=100, layout='constrained'

The return value of subplots() is a tuple(fig, ax)When there is only one row and one column, ax is a single Axes object; with multiple rows and columns, ax is a 2D array of Axes.


Usage Examples

Example 1: Single Subplot

Example

import matplotlib.pyplot as plt
import numpy as np

# Create a single subplot (most common usage)
fig, ax = plt.subplots(figsize=(6, 4), layout='constrained')

x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x))
ax.set_title('Single Subplot')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
ax.grid(True, alpha=0.3)
plt.show()

Example 2: One Row Multiple Columns / One Column Multiple Rows

Example

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

# One row, three columns
fig, axes = plt.subplots(1, 3, figsize=(12, 4),
                          layout='constrained')

# axes is a 1D array
axes[0].plot(x, np.sin(x), color='blue')
axes[0].set_title('sin(x)')

axes[1].plot(x, np.cos(x), color='red')
axes[1].set_title('cos(x)')

axes[2].plot(x, np.tan(x), color='green')
axes[2].set_title('tan(x)')
axes[2].set_ylim(-5, 5)  # Limit y range

for ax in axes:
    ax.set_xlabel('x')
    ax.grid(True, alpha=0.3)

fig.suptitle('Three Subplots in One Row', fontsize=14)
plt.show()

Example 3: 2x2 Grid + Width/Height Ratios

Example

import matplotlib.pyplot as plt
import numpy as np

# Aspect ratio: row 1 is taller, column 2 is wider
fig, axes = plt.subplots(2, 2,
                          figsize=(10, 8),
                          width_ratios=[1, 2],   # Column 2 width is 2 times column 1
                          height_ratios=[2, 1],   # Row 1 height is 2 times row 2
                          layout='constrained',
                          sharex='col',           # Each column shares the x-axis
                          sharey='row')           # Each row shares the y-axis

x = np.linspace(0, 10, 100)

# axes is a 2D array, axes[row, col]
axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title('sin(x)')

axes[0, 1].plot(x, np.cos(x), 'orange')
axes[0, 1].set_title('cos(x)')

axes[1, 0].plot(x, np.sin(2*x), 'green')
axes[1, 0].set_title('sin(2x)')

axes[1, 1].plot(x, np.cos(2*x), 'red')
axes[1, 1].set_title('cos(2x)')

fig.suptitle('2x2 Grid with Width/Height Ratios', fontsize=14)
plt.show()

Example 4: sharex and sharey Shared Axes

Example

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)

# Share the x-axis for easy time series comparison
fig, axes = plt.subplots(3, 1, figsize=(8, 6),
                          sharex=True,            # Share the x-axis
                          layout='constrained')

t = np.linspace(0, 20, 200)

# Three subplots share the x-axis, aligned at the same time points
axes[0].plot(t, np.sin(t), 'blue')
axes[0].set_ylabel('Signal 1')
axes[0].grid(True, alpha=0.3)

axes[1].plot(t, np.cos(t * 1.5), 'green')
axes[1].set_ylabel('Signal 2')
axes[1].grid(True, alpha=0.3)

axes[2].plot(t, np.sin(t * 0.7) + np.cos(t * 1.3), 'red')
axes[2].set_xlabel('Time (s)')
axes[2].set_ylabel('Signal 3')
axes[2].grid(True, alpha=0.3)

fig.suptitle('Shared X-Axis: Three Time Series', fontsize=14)
plt.show()

Example 5: Polar Subplot

Example

import matplotlib.pyplot as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
    subplot_kw={'projection': 'polar'},  # Both are polar coordinates
    layout='constrained')

theta = np.linspace(0, 2 * np.pi, 100)

# Left plot: rose curve
r1 = np.abs(np.sin(3 * theta))
ax1.plot(theta, r1, color='blue', linewidth=2)
ax1.set_title('Polar: Rose Curve (r=|sin(3θ)|)')

# Right plot: Archimedean spiral
r2 = theta / 6
ax2.plot(theta, r2, color='red', linewidth=2)
ax2.set_title('Polar: Archimedean Spiral')

plt.show()

Common Questions

What does the squeeze parameter do?

squeeze=TrueWhen (default):subplots(1,1)returnsax(not [ax]),subplots(1,3)returns a 1D array.

squeeze=FalseWhen, it always returns a 2D array (regardless of row/column count), suitable for scenarios requiring unified processing.

The difference between subplot_kw and gridspec_kw?

subplot_kwPassed to each Axes creation function, such asprojection='polar'。

gridspec_kwPassed to the GridSpec layout manager, such ashspace=0.4(subplot vertical spacing).


Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions