Search code examples
pandasgroup-bycountbar-chart

How to count the values to prepare make stacked bar chart


I'm wondering how to count the values in a column to make a stacked bar chart For example, the data is like below

enter image description here

I'd like to make a stacked bar chart with x="Main", which has the "Detail" values counts. All dtype is object.

What I tried to count the 'Detail' Values is

df['count'] = df['Detail'].value_counts()

But the count column has the value only NaN everytime. enter image description here

Can you share your solution for this?


Solution

  • IIUC, use pd.crosstab and plot.bar:

    pd.crosstab(index=df['Main'], columns=df['Detail']).plot.bar()
    

    Output:

    enter image description here

    Input dataframe given as:

    df = pd.DataFrame({'Main':[*'AAABBBC'],
                       'Detail':[*'aabbcda']})
    

    Or stacked:

    pd.crosstab(index=df['Main'], columns=df['Detail']).plot.bar(stacked=True)
    

    Output:

    enter image description here