0

Say we have a DF like this one below:

channel     store         product  orders
offline     Swindon       webcam   97
offline     Kettering     webcam   28
offline     Swindon       ebook    55
offline     Kettering     ebook    77
offline     Swindon       tablet   122
offline     Kettering     tablet   81
online      Swindon       webcam   252
online      Kettering     webcam   111
online      Swindon       ebook    81
online      Kettering     ebook    244
online      Swindon       tablet   361
online      Kettering     tablet   49

My goal is to get a plot with 4 stacked bars (one for each store & channel combination available) showing the sales percentage each product represents within each one.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
teogj
  • 289
  • 1
  • 11

1 Answers1

2

Easiest would be to first create a pivot table and then plot it:

df.pivot_table(index=["channel", "store"], columns='product', values='orders', aggfunc='sum').plot(kind='bar', stacked=True)

enter image description here

As a matter of fact, you do not even need a pivot_table, because there is no need to do any computation on the data, so you could just reorder the table as such:

df.pivot(index=["channel", "store"], columns='product', values='orders').plot(kind='bar', stacked=True)

and would receive the same result.

divingTobi
  • 2,044
  • 10
  • 25