简体   繁体   English

每个 id 的多线图

[英]Multiline plot for each id

I would like to plot multiple lines in Python for this dataset: (x = year, y = freq)我想在 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

where each student_id has data for different years.其中每个 student_id 都有不同年份的数据。 count is the result of a groupby. count 是 groupby 的结果。 I would like to have one line for each student_id.我希望每个 student_id 都有一行。

I have tried with this:我试过这个:

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

but it does not plot one line for each student_id.但它不会为每个 student_id 绘制一行。

Any suggestions are more than welcome.任何建议都非常受欢迎。 Thank you for your help感谢您的帮助

I wasn't sure from your question if you wanted count (which in your example is all ones) or sum , so I solved this with sum - if you'd like count , just swap it out for sum in the first line.从你的问题中我不确定你是想要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()

Which gives you:这给了你:

在此处输入图片说明

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

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