首页 > 解决方案 > 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

我想要做的是我想在图中用两种颜色制作两条趋势线(联邦和非联邦),以指示每个学年的总值如何变化。

标签: pythonpandasdataframedata-visualization

解决方案


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())

推荐阅读