plt.subplot参数及用法
时间: 2023-07-21 11:02:54 浏览: 98
plt.subplot() 是 Matplotlib 库中用于创建子图的函数。它的参数和用法如下:
参数:
- nrows: 整数,表示子图的行数。
- ncols: 整数,表示子图的列数。
- index: 整数,表示当前子图的索引。子图的索引从左上角开始,从左到右、从上到下递增。
用法:
1. 单个子图:
plt.subplot(111) # 创建一个包含1个子图的画布
2. 多个子图:
plt.subplot(nrows, ncols, index) # 创建包含 nrows 行、ncols 列的子图网格,并选择 index 位置的子图
示例:
```python
import matplotlib.pyplot as plt
# 创建一个2行2列的子图网格,并选择第1个子图
plt.subplot(2, 2, 1)
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.title('Subplot 1')
# 创建一个2行2列的子图网格,并选择第2个子图
plt.subplot(2, 2, 2)
plt.plot([1, 2, 3, 4], [1, 8, 27, 64])
plt.title('Subplot 2')
# 创建一个2行2列的子图网格,并选择第3个子图
plt.subplot(2, 2, 3)
plt.plot([1, 2, 3, 4], [0, -2, -4, -6])
plt.title('Subplot 3')
# 创建一个2行2列的子图网格,并选择第4个子图
plt.subplot(2, 2, 4)
plt.plot([1, 2, 3, 4], [-1, -3, -5, -7])
plt.title('Subplot 4')
plt.tight_layout() # 自动调整子图的布局
plt.show()
```
这段代码会创建一个包含2行2列子图的画布,并在每个子图中绘制不同的曲线。
阅读全文
相关推荐


















