繁体   English   中英

每个 id 的多线图

[英]Multiline plot for each id

我想在 Python 中为此数据集绘制多行:(x = 年,y = 频率)

Student_ID  Year    Freq
A           2012    6
B           2008    22
C           2009    18
A           2010    7
B           2012    13
D           2012    31
D           2013    1

其中每个 student_id 都有不同年份的数据。 count 是 groupby 的结果。 我希望每个 student_id 都有一行。

我试过这个:

df.groupby(['year'])['freq'].count().plot()

但它不会为每个 student_id 绘制一行。

任何建议都非常受欢迎。 感谢您的帮助

从你的问题中我不确定你是想要count (在你的例子中是所有的)还是sum ,所以我用sum解决了这个问题 - 如果你想要count ,只需在第一行将它换成sum

df_ = df.groupby(['Student_ID', 'Year'])['Freq'].sum()
print(df_)

> Student_ID  Year
A           2010     7
            2012     6
B           2008    22
            2012    13
C           2009    18
D           2012    31
            2013     1
Name: Freq, dtype: int64

fig, ax = plt.subplots()
for student in set(a[0] for a in df_.index):
    df_[student].plot(ax=ax, label=student)
    plt.legend()
    plt.show()

这给了你:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM