0

Suppose I have dataframe called "market" which full database of my transaction. I grouped it by each month and product, so I get Sum of sales (USD) for each product/month

test=market.groupby(['Product','Month']).sum()['Sales'].unstack()
test

And the result from above like this

month/product  1   2   3   4   5   6   7   8   9   10   11   12
milk           12  13  12  13  21  21  9   10  15  17   16   20
bread          15  13  13  12  25  24  11  5   13  13   17   14
rice           12  13  15  13  21  21  9   10  19  11   16   25
coffee         12  13  12  16  25  23  11  20  15  14   11   15
tea            15  13  12  13  25  24  11  5   13  8    17   19

How I can make a graph with stacked product sales?

x-axis = month with stacked sales for each product

y-axis = Sales

What I already did:

First Attempt:

fig, sumbu = plt.subplots(figsize=(5,3))
graph=test.plot.bar(stacked='True', ax=sumbu)

plt.xlabel('Month', fontsize='12', color='red')
plt.ylabel('Sales', fontsize='12', color='red')
plt.xticks(rotation=45, size=8)
plt.show(graph)

It run but X-axis is product (I expected month)

Second attempt:

fig, sumbu = plt.subplots(figsize=(5,3))
graph=test.plot.bar(x='Month', y='Sales', stacked=True, ax=sumbu)

plt.xlabel('Month', fontsize='12', color='red')
plt.ylabel('Sales', fontsize='12', color='red')
plt.xticks(rotation=45, size=8)
plt.show(graph)

"KeyError: 'Month'

Ichsan
  • 768
  • 8
  • 12
  • 1
    what columns can be found in the test dataframe? have you tried to look at them via test.info()? Perhaps this could help you in finding the correct name. Also, you could try to transpose the test dataframe to get the months as rows and than make your plot. – Renate van Kempen Feb 10 '20 at 07:56
  • 1
    Also, check this [answer](https://stackoverflow.com/questions/42784930/how-to-plot-a-dataframe-grouped-by-two-columns-in-matplotlib-and-pandas), perhaps it will help you. This says to plot market.groupby(['Product','Month']).sum()['Sales'].unstack().plot.bar(rot=0) or check this [answer](https://stackoverflow.com/questions/42151637/creating-a-grouped-sorted-bar-plot-using-pandas), or [this](https://stackoverflow.com/questions/34225839/groupby-multiple-values-and-plotting-results) – Renate van Kempen Feb 10 '20 at 08:05
  • hey, i tried your advice to transpose that dataframe, it worked well as I want. (stacked product sales per month) – Ichsan Feb 10 '20 at 11:43

1 Answers1

0

After trial and error for 2 hours, I found the answer. You must transpose your dataframe

test2=test.transpose()

fig, sumbu = plt.subplots(figsize=(5,3))
graph=test2.plot.bar(stacked='True', ax=sumbu)

plt.xlabel('Month', fontsize='12', color='red')
plt.ylabel('Sales', fontsize='12', color='red')
plt.xticks(rotation=45, size=8)
plt.show(graph)
Ichsan
  • 768
  • 8
  • 12