# 在 Matplotlib 中添加子图

Suraj Joshi 2024年2月15日

## 使用 `matplotlib.pyplot.figure.add_subplot()` 方法在图中添加子图

``````import matplotlib.pyplot as plt

fig = plt.figure(figsize=(5, 5))

x = [1, 2, 3, 4, 5]
y = [2, 4, 5, 1, 2]

subplot.plot(x, y)

fig.suptitle("Figure with only one Subplot")
plt.show()
``````

``````import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 6))

ax_1.text(0.3, 0.5, "subplot(121)")

ax_2.text(0.3, 0.5, "subplot(222)")

ax_3.text(0.3, 0.5, "subplot(224)")

fig.suptitle("Figure with multiple Subplots")
plt.show()
``````

## 使用 `Matplotlib.pyplot.subplots()` 创建带有子图的图

`Matplotlib.pyplot.subplots()` 也可以给图添加子图。我们将行数和列数作为参数传递给该方法，该方法返回一个图对象和轴对象，可以用来操作图形。

``````import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 1)

ax[0].text(0.3, 0.5, "1st Subplot")
ax[0].set_xticks([])
ax[0].set_yticks([])

ax[1].text(0.3, 0.5, "2nd Subplot")
ax[1].set_xticks([])
ax[1].set_yticks([])

fig.suptitle("Figure with 2 subplots", fontsize=16)
plt.show()
``````

``````import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [i ** 2 for i in x]
y2 = [4 * i + 1 for i in x]

fig, ax = plt.subplots(2, 1)

ax[0].plot(x, y1)
ax[0].set_xlabel("X")
ax[0].set_ylabel("Y")

ax[1].plot(x, y2)
ax[1].set_xlabel("X")
ax[1].set_ylabel("Y")

plt.tight_layout()
plt.show()
``````

Suraj Joshi is a backend software engineer at Matrice.ai.