python - Python pandas 绘制多条线
问题描述
我想在图中制作两条趋势线。我写了一个代码,但它没有按预期工作。有没有其他方法可以做到这一点?
by_type = df.filter(["Total","Academic_Year","Institute_Type"]).groupby(["Institute_Type","Academic_Year"]).sum()
print(by_type)
by_type=df.pivot(index='Academic_Year', columns='Institute_Type', values='Total')
by_type.plot()
这是打印命令的结果。
Institute_Type Academic_Year Total
Federal 2012-2013 83302.0
2013-2014 90770.0
2014-2015 95230.0
2015-2016 92828.0
2016-2017 93274.0
2017-2018 93424.0
2018-2019 92442.0
2019-2020 89632.0
Non-Federal 2012-2013 153084.0
2013-2014 165788.0
2014-2015 183580.0
2015-2016 186290.0
2016-2017 181236.0
2017-2018 180298.0
2018-2019 170436.0
2019-2020 172996.0
但是枢轴命令给了我一个错误
ValueError: Index contains duplicate entries, cannot reshape
我想要做的是我想在图中用两种颜色制作两条趋势线(联邦和非联邦),以指示每个学年的总值如何变化。
解决方案
import matplotlib.pyplot as plt
# Convert back to single dataframe instead of groups
df = by_type.apply(pd.DataFrame)
# Loop through, grouping by JUST Institute_Type
for Institute_Type, vals in df.groupby('Institute_Type'):
vals.plot(x='Academic_Year', y='Total', kind='line',
label=Institute_Type, ax=plt.gca())
推荐阅读
- google-apps-script - 来自脚本的 Google 表单,试图获取每行一个响应的 addCheckboxGridItem 选项
- c - 如何设计和实现在 C 中触发部分代码的可调度警报/事件
- python - 在虚拟环境中运行 Pyomo 时出错
- java - 解析包时出错:以编程方式从服务器下载后尝试安装 apk
- android - firebase 项目中的应用实例是什么?它是唯一用户的应用程序还是应用程序?
- javascript - 使用 selenium 抓取 javascript 内容
- java - 打包结构化 Spring 项目的最佳实践是什么?
- javascript - Angular7 应用无法在 Safari 浏览器中运行
- google-apps-script - 有什么办法可以让我向上搜索价值吗?
- javascript - 检查变量是否未定义的更好方法是什么?