0

I would like to create a stacked bar chart showing for each Day_Since_Acquisition the number of Total_Customers for each Aquisition_Channel.

I am having issues creating a stacked bar plot out of this df that show on the X-axis on the values for Day_Since_Acquisition and nothing in between.

DF

Aquisition_Channel   Day_Since_Acquisition  Total_Customers
Digital              7                       10
Digital              14                      12
Digital              21                      16
Digital              28                      20
Organic              7                       32
Organic              14                      40
Organic              21                      41
Organic              28                      45
Offline              7                       23
Offline              14                      30
Offline              21                      46
Offline              28                      55

This is my current code:

fig = px.bar(df, x="Day_Since_Acquisition", y="Total_Customers",
             color="Day_Since_Acquisition", barmode = 'stack')
 
fig.show()
user12625679
  • 676
  • 8
  • 23

1 Answers1

1
df2 = df.groupby(["Day_Since_Acquisition","Aquisition_Channel"]).sum().unstack("Aquisition_Channel").fillna(0)
df2["Total_Customers"].plot.bar(stacked=True)

The output chart is:

enter image description here

not_speshal
  • 22,093
  • 2
  • 15
  • 30
  • how can I display the values for each acquisition channel? – user12625679 Jun 02 '21 at 13:42
  • 1
    See this very detailed (and excellent) [answer](https://stackoverflow.com/a/64202669/9857631) and adapt your code as necessary – not_speshal Jun 02 '21 at 14:14
  • @user12625679 Since no values are being aggregated with `.sum()`, the correct implementation is to use `.pivot()`. `dfp = df.pivot(index='Day_Since_Acquisition', columns='Aquisition_Channel', values='Total_Customers')` and then `dfp.plot(kind='bar', stacked=True)` – Trenton McKinney Jun 02 '21 at 16:32