fredooms
fredooms

Reputation: 123

barplot with 2 columns

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

Answers (1)

mozway
mozway

Reputation: 261860

You have three options.

using pandas:

dfObj.groupby('Type')['q'].value_counts().plot(kind='barh')

pandas bar plot

using pandas stacked bars:

dfObj.groupby('Type')['q'].value_counts().unstack(level=0).plot.barh(stacked=True)

pandas stacked bars

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')

seaborn catplot

Upvotes: 2

Related Questions