用pandas写一个包含两个Y轴的折线图并展示
时间: 2024-06-10 17:05:14 浏览: 94
双Y轴折线图(原创)
4星 · 用户满意度95%
好的,您可以通过以下代码来画一个包含两个 Y 轴的折线图:
``` python
import pandas as pd
import matplotlib.pyplot as plt
# 构造数据
data1 = {'year': [2010, 2011, 2012, 2013, 2014, 2015],
'production': [105, 120, 130, 160, 180, 200]}
data2 = {'year': [2010, 2011, 2012, 2013, 2014, 2015],
'income': [2000, 2400, 2700, 3000, 3400, 4000]}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
# 绘制折线图
fig, ax1 = plt.subplots()
line1 = ax1.plot(df1['year'], df1['production'], label='Production', color='b')
ax2 = ax1.twinx()
line2 = ax2.plot(df2['year'], df2['income'], label='Income', color='r')
# 调整图例,x轴和y轴标签
lines = line1 + line2
labels = [l.get_label() for l in lines]
ax1.legend(lines, labels, loc='lower right')
ax1.set_xlabel('Year')
ax1.set_ylabel('Production (units)', color='b')
ax2.set_ylabel('Income (dollars)', color='r')
# 显示图表
plt.show()
```
此代码将生成一个如下图所示的折线图,其中生产数据在左轴上显示(蓝色),收入数据在右轴上显示(红色)。
![image](https://img-blog.csdn.net/20180519182346673?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2ZhY2FkYXJfMTIz/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
阅读全文