Ash Fleming
Ash Fleming

Reputation: 11

Plotting stacked bar chart

I'm trying to create a stacked bar chart, with xaxis = 'customer_id(count), yaxis = 'age_band', and the 3 different loyalty groups stacked in the chart (hue), so I should see 6 bars each with 2-3 different colours.

code I've tried:

df.groupby(['age_band','loyalty']).agg(Loyalty=('customer_id', pd.Series.nunique)).plot(kind='bar', stacked=True)

Picture for reference: data frame & current bar chart

Upvotes: 0

Views: 49

Answers (1)

jezrael
jezrael

Reputation: 862406

IIUC use DataFrame.pivot_table:

(df.pivot_table(index='age_band',columns='loyalty', values='customer_id', aggfunc='nunique')
       .plot(kind='bar', stacked=True))

Upvotes: 2

Related Questions