I have a dataframe like this:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
df = pd.DataFrame({'category': list('XYZXY'), 'B': range(5,10),'sex': list('mfmff')})
I want to plot count of sex male or female based on category from column 'category'.
I tried:
df.groupby(['category','sex'])['category','sex'].count().plot.bar()
How to get the count of sex per category?
Using groupby+unstack:
df.groupby(['sex','category'])['B'].count().unstack('sex').plot.bar()
Using pivot_table:
pd.pivot_table(df, values = 'B', index = 'category',
columns = 'sex',aggfunc ='count').plot.bar()
Using seaborn:
import seaborn as sns
sns.countplot(data=df,x='category',hue='sex')
or,
sns.catplot(data=df,kind='count',x='category',hue='sex')
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments