Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this grouped data frame don't show the expected plot?

Tags:

python

pandas

I have this pandas data frame, where I want to make a line plot, per each year strata:

    year    month   canasta
0   2011    1   239.816531
1   2011    2   239.092353
2   2011    3   239.332308
3   2011    4   237.591538
4   2011    5   238.384231
... ... ... ...
59  2015    12  295.578605
60  2016    1   296.918861
61  2016    2   296.398701
62  2016    3   296.488780
63  2016    4   300.922927

And I tried this code:

dca.groupby(['year', 'month'])['canasta'].mean().reset_index().plot()

But I get this result: enter image description here

I must be doing something wrong. Please, could you help me with this plot? The x axis is the months, and there should be a line per each year.

like image 576
Alexis Avatar asked Dec 19 '25 10:12

Alexis


1 Answers

Why: Because after you do reset_index, year and month become normal columns. And some_df.plot() simply plots all the columns of the dataframe into one plot, resulting what you posted.

Fix: Try unstack instead of reset_index:

(dca.groupby(['year', 'month'])
    ['canasta'].mean()
    .unstack('year').plot()
)
like image 102
Quang Hoang Avatar answered Dec 21 '25 00:12

Quang Hoang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!