python一个图中绘制多个折线图
时间: 2023-12-12 20:52:47 浏览: 95
可以使用matplotlib库来实现在一个图中绘制多个折线图。
首先,导入必要的库和生成数据:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
```
然后,创建一个figure对象和axes对象:
```python
fig, ax = plt.subplots()
```
接着,在ax对象上绘制三个折线图:
```python
ax.plot(x, y1, label='sin(x)')
ax.plot(x, y2, label='cos(x)')
ax.plot(x, y3, label='tan(x)')
```
最后,添加图例和设置标题等:
```python
ax.legend()
ax.set_title('Multiple Line Plots')
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.show()
```
完整代码如下:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
# 创建figure对象和axes对象
fig, ax = plt.subplots()
# 在ax对象上绘制三个折线图
ax.plot(x, y1, label='sin(x)')
ax.plot(x, y2, label='cos(x)')
ax.plot(x, y3, label='tan(x)')
# 添加图例和设置标题等
ax.legend()
ax.set_title('Multiple Line Plots')
ax.set_xlabel('x')
ax.set_ylabel('y')
# 显示图像
plt.show()
```
阅读全文