subplot 如何使用
时间: 2024-01-20 09:02:54 浏览: 35
subplot 是 Matplotlib 库中的一个函数,用于在同一个 figure 中创建多个子图。它通常用于将多个图形放在同一个窗口中进行比较或显示。
subplot 的基本语法如下:
```python
import matplotlib.pyplot as plt
fig = plt.figure() # 创建一个新的 figure
ax1 = fig.add_subplot(nrows, ncols, index) # 在 figure 中添加一个子图
# 绘制第一个子图
ax1.plot(x1, y1)
ax2 = fig.add_subplot(nrows, ncols, index) # 在 figure 中添加另一个子图
# 绘制第二个子图
ax2.plot(x2, y2)
# 显示图形
plt.show()
```
其中,`nrows` 和 `ncols` 分别表示子图的行数和列数,`index` 表示当前子图的位置。子图的位置是从左到右、从上到下依次编号的,从 1 开始。
例如,下面的代码创建了一个 2x2 的子图,绘制了四幅图形:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成数据
x = np.linspace(0, 2*np.pi, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = np.exp(x)
# 创建 figure 和 subplot
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)
# 绘制子图
ax1.plot(x, y1)
ax2.plot(x, y2)
ax3.plot(x, y3)
ax4.plot(x, y4)
# 显示图形
plt.show()
```
这段代码将会创建一个 2x2 的子图,其中第一行为 sin 和 cos 的曲线,第二行为 tan 和 exp 的曲线。每个子图的大小相等,且在同一个窗口中显示。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)