# 如何在 Matplotlib 中为所有子图设置一个主标题

Suraj Joshi 2023年1月30日

## `pyplot.suptitle()` 为所有 Matplotlib 子图添加主标题

``````import numpy as np
import matplotlib.pyplot as plt

m1 = 1
c1 = 0

m2 = 2
c2 = 2

m3 = 2
c3 = 1

m4 = 1
c4 = 2

x = np.linspace(0, 3, 100)
y1 = m1 * x + c1
y2 = m2 * x + c2
y3 = m3 * x + c3
y4 = m4 * x + c4

fig, ax = plt.subplots(2, 2, figsize=(10, 8))

ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x, y4)

ax[0, 0].set_title("Line-1")
ax[0, 1].set_title("Line-2")
ax[1, 0].set_title("Line-3")
ax[1, 1].set_title("Line-4")

plt.suptitle("Various Straight Lines", fontsize=20)

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

## `figure.suptitle()` 为所有 Matplotlib 子图添加主标题

``````import numpy as np
import matplotlib.pyplot as plt

m1 = 1
c1 = 0

m2 = 2
c2 = 2

m3 = 2
c3 = 1

m4 = 1
c4 = 2

x = np.linspace(0, 3, 100)
y1 = m1 * x + c1
y2 = m2 * x + c2
y3 = m3 * x + c3
y4 = m4 * x + c4

fig, ax = plt.subplots(2, 2, figsize=(10, 8))

ax[0, 0].plot(x, y1)
ax[0, 1].plot(x, y2)
ax[1, 0].plot(x, y3)
ax[1, 1].plot(x, y4)

ax[0, 0].set_title("Line-1")
ax[0, 1].set_title("Line-2")
ax[1, 0].set_title("Line-3")
ax[1, 1].set_title("Line-4")

fig.suptitle("Various Straight Lines", fontweight="bold")

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

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