对于这样的事情,一个有用的函数是plt.subplots(nrows, ncols)
它将返回规则网格上子图的数组(numpy 对象数组)。
举个例子:
import matplotlib.pyplot as plt
import numpy as np
fig, axes = plt.subplots(nrows=4, ncols=4, sharex=True, sharey=True)
# "axes" is a 2D array of axes objects. You can index it as axes[i,j]
# or iterate over all items with axes.flat
# Plot on all axes
for ax in axes.flat:
x, y = 10 * np.random.random((2, 20))
colors = np.random.random((20, 3))
ax.scatter(x, y, s=80, facecolors=colors, edgecolors='')
ax.set(xticks=np.linspace(0, 10, 6), yticks=np.linspace(0, 10, 6))
# Operate on just the top row of axes:
for ax, label in zip(axes[0, :], ['A', 'B', 'C', 'D']):
ax.set_title(label, size=20)
# Operate on just the first column of axes:
for ax, label in zip(axes[:, 0], ['E', 'F', 'G', 'H']):
ax.set_ylabel(label, size=20)
plt.show()