以dataframe第一列为x轴,画出第2、3、4、5列的折线图,其中4、5列用另一个y轴
时间: 2024-09-23 07:02:28 浏览: 51
在Python的pandas库和matplotlib库结合下,你可以通过以下步骤创建这样的图形:
首先,你需要导入必要的库:
```python
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
# 假设df是你的DataFrame对象
```
然后,设置数据框的前两列为x轴的数据,其余列作为y轴的数据,并创建两个y轴:
```python
host = host_subplot(111) # 创建主坐标轴
par1 = host.twinx() # 创建第一个副坐标轴(用于前两列)
par2 = par1.twinx() # 创建第二个副坐标轴(用于后两列)
# 分别提取需要的列数据
x_data = df.iloc[:, 0]
y1_data = df.iloc[:, 1:3] # 第2列和第3列
y2_data = df.iloc[:, 3:5] # 第4列和第5列
# 绘制折线图
host.set_xlabel('X轴')
host.set_ylabel('Y轴1', color='tab:blue') # 主坐标轴的Y1颜色
par1.set_ylabel('Y轴2', color='tab:red') # 副坐标轴1的Y2颜色
par2.set_ylabel('Y轴3', color='tab:green') # 副坐标轴2的Y3颜色
host.plot(x_data, y1_data, label='Y轴1', color='blue')
par1.plot(x_data, y2_data[:, 0], label='Y轴2', color='red')
par2.plot(x_data, y2_data[:, 1], label='Y轴3', color='green')
# 设置图例和整理轴刻度
lines, labels = host.get_legend_handles_labels()
lines2, labels2 = par1.get_legend_handles_labels()
lines3, labels3 = par2.get_legend_handles_labels()
host.legend(lines + lines2 + lines3, labels + labels2 + labels3)
plt.show()
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)