# 如何在 Matplotlib 中向子图添加标题

Suraj Joshi 2023年1月30日 2020年6月9日 Matplotlib Matplotlib Subplot

## 使用 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()
``````
Author: Suraj Joshi

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