How to plot such a graph with matplotlib

Viewed 57

I have a dataframe:

  date       date2      col1   col2
 
2011-05-01  2011-05-01    3     25
            2011-05-02    1     17
            2011-05-03    2     12

2012-05-01  2012-05-01    5     45
            2012-05-02    5     73

How can I plot each column (col1 and col2) grouping dataframe by level 0 (date)?

I want to get a graph like this one in the picture. So date is determined by color, date2 is on x-axis and col1 or col2 are the cols I what to plot separately.

I tried stackplot, but it didn't work, as I can't set the x length:

plt.stackplot(df.date2,df.groupby(level=0)['col1'].sum())

Picture I want to receive:

enter image description here

Thank you

1 Answers

Try this using dataframe reshaping:

df.unstack('date2')['col1'].plot.area()

As @QuangHoang states, this is less costly, you are manipulating fewer columns, this is better:

df['col1'].unstack('date2').plot.area()
Related