2

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

3
  • 3
    Try this: df.unstack('date2')['col1'].plot.area().. not enough data to duplicate your plot. Commented Sep 28, 2020 at 19:20
  • 1
    Thank you. It works. Commented Sep 28, 2020 at 19:24
  • @user12628549 Please consider accepting and upvoting the answer if works for you. Commented Sep 28, 2020 at 19:28

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

2 Comments

Upvoted. df['col1'].unstack('date2').plot.area() is a little less costly.
Thanks, @QuangHoang. Be safe and stay healthy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.