matplotlib多子图设置x标签
时间: 2023-07-01 13:16:56 浏览: 66
在 Matplotlib 中,设置子图的 x 轴标签可以使用 `set_xlabel()` 方法。下面是一个简单的例子:
```python
import matplotlib.pyplot as plt
# 创建一个 2x2 的子图
fig, axs = plt.subplots(2, 2)
# 在第一个子图中画图
axs[0, 0].plot([1, 2, 3], [4, 5, 6])
axs[0, 0].set_xlabel('X Label 1')
# 在第二个子图中画图
axs[0, 1].plot([1, 2, 3], [6, 5, 4])
axs[0, 1].set_xlabel('X Label 2')
# 在第三个子图中画图
axs[1, 0].plot([1, 2, 3], [2, 4, 6])
axs[1, 0].set_xlabel('X Label 3')
# 在第四个子图中画图
axs[1, 1].plot([1, 2, 3], [6, 4, 2])
axs[1, 1].set_xlabel('X Label 4')
plt.show()
```
在上面的代码中,我们使用 `set_xlabel()` 方法来设置 x 轴标签。
如果你想要对所有子图设置相同的 x 轴标签,可以在 `fig.supxlabel()` 方法中指定标签。示例如下:
```python
import matplotlib.pyplot as plt
# 创建一个 2x2 的子图
fig, axs = plt.subplots(2, 2)
# 在第一个子图中画图
axs[0, 0].plot([1, 2, 3], [4, 5, 6])
# 在第二个子图中画图
axs[0, 1].plot([1, 2, 3], [6, 5, 4])
# 在第三个子图中画图
axs[1, 0].plot([1, 2, 3], [2, 4, 6])
# 在第四个子图中画图
axs[1, 1].plot([1, 2, 3], [6, 4, 2])
# 设置 x 轴标签
fig.supxlabel('X Label')
plt.show()
```
在上面的代码中,我们使用 `fig.supxlabel()` 方法来设置 x 轴标签。