notarealgreal
notarealgreal

Reputation: 686

Pandas Dataframe Create Seaborn Horizontal Barplot with categorical data

I'm currently working with a data frame like this:

enter image description here

What I want is to show the total numer of the Victory column where the value is S grouped by AGE_GROUP and differenced by GENDER, something like in the following horizontal barplot:

enter image description here

Until now I could obtain the following chart:

enter image description here

Following this steps:

victory_df = main_df[main_df["VICTORY"] == "S"]
victory_count = victory_df["AGE_GROUP"].value_counts()
sns.set(style="darkgrid")
sns.barplot(victory_count.index, victory_count.values, alpha=0.9)

Which strategy I should use to difference in the value_count by gender and include it in the chart?

Upvotes: 0

Views: 404

Answers (1)

wwnde
wwnde

Reputation: 26676

It would obviously help giving raw data and not an image. Came up with own data.Not sure understood your question but my attempt below.

Data

df=pd.DataFrame.from_dict({'VICTORY':['S', 'S', 'N', 'N', 'N', 'S', 'N', 'S', 'N', 'S', 'N', 'S', 'S'],'AGE':[5., 88., 12., 19., 30., 43., 77., 50., 78., 34., 45.,  9., 67.],'AGE_GROUP':['0-13', '65+', '0-13', '18-35', '18-35', '36-64', '65+', '36-64','65+', '18-35', '36-64', '0-13', '65+'],'GENDER':['M', 'M', 'F', 'M', 'F', 'F', 'M', 'F', 'F', 'F', 'M', 'M', 'F']})

Plotting. I groupby AGE_GROUP, value count GENDER, unstack and plot a stacked horizontal bar plot. Seaborn is build on matplotlib and when plotting is not straightforward in seaborn like the stacked horizontal bar, I fall back to matplotlib. Hope you dont take offence.

   df[df['VICTORY']=='S'].groupby('AGE_GROUP')['GENDER'].apply(lambda x: x.value_counts()).unstack().plot(kind='barh', stacked=True)

plt.xlabel('Count')
plt.title('xxxx')

Output

enter image description here

Upvotes: 1

Related Questions