简体   繁体   中英

Multiline plot for each id

I would like to plot multiple lines in Python for this dataset: (x = year, y = freq)

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. count is the result of a groupby. I would like to have one line for each student_id.

I have tried with this:

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

but it does not plot one line for each 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.

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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