# 如何在 Matplotlib 中向子圖新增標題

Suraj Joshi 2024年2月15日

## 使用 set_title()方法將標題新增到 Matplotlib 中的子圖

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

x = np.linspace(-3, 3, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = 1 / (1 + np.exp(-x))
y4 = np.exp(x)

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

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("Sine function")
ax[0, 1].set_title("Cosine function")
ax[1, 0].set_title("Sigmoid function")
ax[1, 1].set_title("Exponential function")

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

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

x = np.linspace(-3, 3, 100)
y = [0, 0, 0, 0]
y[0] = np.sin(x)
y[1] = np.cos(x)
y[2] = 1 / (1 + np.exp(-x))
y[3] = np.exp(x)

figure, ax = plt.subplots(2, 2)
i = 0
for a in range(len(ax)):
for b in range(len(ax[a])):
ax[a, b].plot(x, y[i])
subplot_title = "Subplot" + str(i)
ax[a, b].set_title(subplot_title)
i = i + 1

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

## 使用 `title.set_text()` 方法設定 Matplotlib 子圖的標題

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

x = np.linspace(-3, 3, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = 1 / (1 + np.exp(-x))
y4 = np.exp(x)

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

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].title.set_text("Sine function")
ax[0, 1].title.set_text("Cosine function")
ax[1, 0].title.set_text("Sigmoid function")
ax[1, 1].title.set_text("Exponential function")

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

## `plt.gca().set_title()` / `plt.gca.title.set_text()` 將標題設定為 Matplotlib 中的子圖

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

plt.subplots(2, 2)
x = [1, 2, 3]
y = [2, 4, 6]

for i in range(4):
plt.subplot(2, 2, i + 1)
plt.plot(x, y)
plt.gca().set_title("Title-" + str(i))

plt.show()

plt.tight_layout()
``````

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

plt.subplots(2, 2)
x = [1, 2, 3]
y = [2, 4, 6]

for i in range(4):
plt.subplot(2, 2, i + 1)
plt.plot(x, y)
plt.gca().title.set_text("Title-" + str(i))

plt.show()

plt.tight_layout()
``````

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