Home > OS >  Make stacked barplot using pandas
Make stacked barplot using pandas

Time:02-05

I have the following dataframe:

    condition       area
Month
Oct           Poor  11.386331
Oct          Better  65.483997
Oct     Favourable   5.165156
Oct    Exceptional  17.964516
Nov           Poor  14.589887
Nov          Better 62.965886
Nov     Favourable   4.942206
Nov    Exceptional  17.502020
Dec           Poor  29.718102
Dec          Better 52.317383
Dec     Favourable  10.754567
Dec    Exceptional   7.209948

I want to create a stacked bar plot, where for each month, each element of the stacked bar plot shows the corresponding area. However, when I do this:

df.plot(kind='bar', stacked=True, color=['orangered', 'yellow', 'limegreen', 'dodgerblue'])

I get: enter image description here

CodePudding user response:

The problem with the code is, that df.plot.bar() does not group the index of your Dataframe and stacks only multiply columns for the same index.

For your task you have to rearrange your data. For this use reset_index and stacked bar plot

If you print you DataFrame after pivot() it looks like this.

condition     Better  Exceptional  Favourable       Poor
Month     
Dec        52.317383     7.209948   10.754567  29.718102
Nov        62.965886    17.502020    4.942206  14.589887
Oct        65.483997    17.964516    5.165156  11.386331
  •  Tags:  
  • Related