在Python中如何将几条曲线绘制在一个figure中
时间: 2024-02-01 19:13:50 浏览: 32
在Python中,可以使用Matplotlib库来将几条曲线绘制在一个figure中。具体步骤如下:
1. 导入Matplotlib库:
```
import matplotlib.pyplot as plt
```
2. 创建一个figure对象:
```
fig = plt.figure()
```
3. 在figure对象中添加子图:
```
ax = fig.add_subplot(111)
```
其中,111表示将整个figure分成1行1列的1个子图,ax表示子图对象。
4. 绘制曲线:
```
x = [1, 2, 3, 4, 5]
y1 = [1, 3, 2, 4, 5]
y2 = [2, 4, 1, 3, 6]
ax.plot(x, y1)
ax.plot(x, y2)
```
其中,x表示横坐标的数据,y1和y2分别表示两条曲线的纵坐标数据,ax.plot()函数用于绘制曲线。
5. 显示图像:
```
plt.show()
```
完整的代码如下:
```
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x = [1, 2, 3, 4, 5]
y1 = [1, 3, 2, 4, 5]
y2 = [2, 4, 1, 3, 6]
ax.plot(x, y1)
ax.plot(x, y2)
plt.show()
```
运行该代码可以得到两条曲线分别绘制在同一个figure中的效果图。