subplot在python中的用法
时间: 2023-11-21 13:42:55 浏览: 99
在Python中,`subplot`是Matplotlib库中的一个函数,用于创建一个子图,并将其放置在一个大的图中。
`subplot` 函数的语法为:
```python
subplot(nrows, ncols, index, **kwargs)
```
其中:
- `nrows`:子图的行数。
- `ncols`:子图的列数。
- `index`:当前子图的编号,从左上角开始,从左到右、从上到下依次编号,范围为 1 到 nrows x ncols。
- `**kwargs`:其他关键字参数,用于设置当前子图的属性,比如设置标题、坐标轴等。
下面是一个示例代码,演示了如何使用 `subplot` 函数创建一个子图:
```python
import matplotlib.pyplot as plt
import numpy as np
# 创建一个 2x2 的图,当前子图编号为 1
plt.subplot(2, 2, 1)
# 绘制一个 sin 曲线
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
# 设置子图标题和坐标轴标签
plt.title('Sin Curve')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# 创建第二个子图,并绘制一个 cos 曲线
plt.subplot(2, 2, 2)
y = np.cos(x)
plt.plot(x, y)
# 设置第二个子图的标题和坐标轴标签
plt.title('Cos Curve')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# 显示图形
plt.show()
```
运行上述代码,将会得到一个 2x2 的图,其中第一个子图绘制了 sin 曲线,第二个子图绘制了 cos 曲线。图形如下所示:

阅读全文
相关推荐


















