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'

3
  • 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. Commented Feb 10, 2020 at 7:56
  • 1
    Also, check this answer, perhaps it will help you. This says to plot market.groupby(['Product','Month']).sum()['Sales'].unstack().plot.bar(rot=0) or check this answer, or this Commented Feb 10, 2020 at 8:05
  • hey, i tried your advice to transpose that dataframe, it worked well as I want. (stacked product sales per month) Commented Feb 10, 2020 at 11:43

1 Answer 1

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

Comments

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.