Reputation: 123
I would like to create barplot horizontal with the following dataframe
studentData = {
0 : {
'stylevel' : 'bachelor',
'q' : 'agree',
'Type' : 'Nascent'
},
1 : {
'stylevel' : 'bachelor',
'q' : 'very',
'Type' : 'Nascent'
},
2 : {
'stylevel' : 'master',
'q' : 'very',
'Type' : 'Active'
},
3 : {
'stylevel' : 'master',
'q' : 'agree',
'Type' : 'Active'
},
4 : {
'stylevel' : 'master',
'q' : 'agree',
'Type' : 'Student'
},
}
dfObj = pd.DataFrame(studentData)
dfObj = dfObj.T
I'm using the following code to plot the graph
dfObj['q'].value_counts().plot(kind='barh')
Could you tell me how I could create the same graph using the Type column in the original dataframe to split the q data in 3 subgroups (i.e. Student, Active and nascent)?
Upvotes: 2
Views: 134
Reputation: 261860
You have three options.
using pandas:
dfObj.groupby('Type')['q'].value_counts().plot(kind='barh')
using pandas stacked bars:
dfObj.groupby('Type')['q'].value_counts().unstack(level=0).plot.barh(stacked=True)
using seaborn.catplot
:
import seaborn as sns
df2 = dfObj.groupby('Type')['q'].value_counts().rename('count').reset_index()
sns.catplot(data=df2, x='q', hue='Type', y='count', kind='bar')
Upvotes: 2