Reputation: 133
I have a dataframe which looks like :
|---------------------|------------------|------------------|
| Gender | Male | Female |
|---------------------|------------------|------------------|
| Scenario | | |
|---------------------|------------------|------------------|
| A | 79 | 217 |
|---------------------|------------------|------------------|
| B | 59 | 408 |
|---------------------|------------------|------------------|
| C | 420 | 330 |
|---------------------|------------------|------------------|
| D | 208 | 1330 |
I would like to plot a seaborn percent bar graph, it should be a single bar which should represent the percent of female i.e. for Scenario A the bar should show 217/(217+79) and so on. How can i achieve this. I am able to plot stacked bar or side by side bar from the following code.
stacked = my_dataframe.stack().reset_index().rename(columns={0:'value'})
# plot grouped bar chart
sns.barplot(x=stacked.Scenario, y=stacked.value, hue=stacked.Gender)
plt.show()
Upvotes: 0
Views: 481
Reputation: 2689
not my most elegant code, but this works:
import pandas as pd
stacked = pd.DataFrame({'Scenario': list('ABCD'), 'Male': [79, 59, 420, 208], 'Female': [217, 408, 330, 1330]})
pd.DataFrame(stacked.apply(lambda x: {'Scenario': x.Scenario, 'Male_pct': x.Male / (x.Male + x.Female), 'Female_pct': x.Female / (x.Male + x.Female)}, axis=1,).tolist())
then just plot it how you were plotting already.
Upvotes: 1