使用matplotlib库绘制包含两条折线的折线图
时间: 2023-07-11 17:05:08 浏览: 127
好的,以下是使用Matplotlib库绘制包含两条折线的折线图的示例代码:
```python
import matplotlib.pyplot as plt
# 定义数据
x = [1, 2, 3, 4, 5]
y1 = [3, 5, 2, 7, 4]
y2 = [2, 4, 6, 8, 10]
# 绘制折线图
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')
# 设置横轴和纵轴标签
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# 设置标题
plt.title('Two Lines Graph')
# 显示图例
plt.legend()
# 显示图形
plt.show()
```
运行以上代码,可以得到一张包含两条折线的折线图,如下所示:

相关问题
使用matplotlib库绘制散点图,折线图,直方图,饼状图
好的,以下是使用matplotlib库绘制散点图、折线图、直方图、饼状图的示例代码:
### 散点图
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 3, 5]
plt.scatter(x, y)
plt.show()
```
### 折线图
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 3, 5]
plt.plot(x, y)
plt.show()
```
### 直方图
```python
import matplotlib.pyplot as plt
import numpy as np
data = np.random.normal(size=1000)
plt.hist(data, bins=30)
plt.show()
```
### 饼状图
```python
import matplotlib.pyplot as plt
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
plt.pie(sizes, labels=labels)
plt.show()
```
以上代码仅为示例,你可以根据自己的需求进行修改和优化。
使用matplotlib库绘制折线图
好的,以下是绘制折线图的示例代码:
```python
import matplotlib.pyplot as plt
# 定义 x 和 y 坐标
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# 绘制折线图
plt.plot(x, y)
# 添加标题和坐标轴标签
plt.title('Line chart')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# 显示图形
plt.show()
```
这是一个简单的示例,你可以根据自己的需求修改 x 和 y 坐标的值,以及添加更多的样式和标签。
阅读全文
相关推荐














