I'm wondering how to count the values in a column to make a stacked bar chart For example, the data is like below
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.
Can you share your solution for this?
IIUC, use pd.crosstab
and plot.bar
:
pd.crosstab(index=df['Main'], columns=df['Detail']).plot.bar()
Output:
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: