matplotlib绘图使用
时间: 2024-04-12 07:26:12 浏览: 12
matplotlib是一个用于绘制数据可视化的Python库[^1]。下面是两种使用matplotlib绘图的方法:
1. 使用subplot()方法绘制多个子图:
```python
import matplotlib.pyplot as plt
# 创建一个2x2的子图布局,选择第一个子图
plt.subplot(2, 2, 1)
plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) # 绘制曲线
# 选择第二个子图
plt.subplot(2, 2, 2)
plt.plot([1, 2, 3, 4], [1, 2, 3, 4]) # 绘制曲线
# 选择第三个子图
plt.subplot(2, 2, 3)
plt.plot([1, 2, 3, 4], [4, 3, 2, 1]) # 绘制曲线
# 选择第四个子图
plt.subplot(2, 2, 4)
plt.plot([1, 2, 3, 4], [1, 8, 27, 64]) # 绘制曲线
# 显示图形
plt.show()
```
2. 使用subplots()方法绘制多个子图:
```python
import matplotlib.pyplot as plt
# 创建一个2x2的子图布局
fig, axs = plt.subplots(2, 2)
# 在第一个子图中绘制曲线
axs[0, 0].plot([1, 2, 3, 4], [1, 4, 9, 16])
# 在第二个子图中绘制曲线
axs[0, 1].plot([1, 2, 3, 4], [1, 2, 3, 4])
# 在第三个子图中绘制曲线
axs[1, 0].plot([1, 2, 3, 4], [4, 3, 2, 1])
# 在第四个子图中绘制曲线
axs[1, 1].plot([1, 2, 3, 4], [1, 8, 27, 64])
# 显示图形
plt.show()
```