Home > OS >  Python code to make bar plot grouped by categorical variable (gender)
Python code to make bar plot grouped by categorical variable (gender)

Time:09-06

I have a dataframe like this: dataframe The dataframe is made by a groupby function and thereafter I have reset the index. I'm trying to make a barplot with each score/grade grouped by gender. Thus 4 groups of bars. With this code I don't get the desired output. data_gender.plot(x='gender',kind='bar', stacked=False)

CodePudding user response:

maybe this, considering a dataframe named df to plot math_score, for other variables just replace the name

import seaborn as sns

sns.barplot(x="gender", y="math_score", data=df)

CodePudding user response:

You could transpose your DF and use gender as index. try something like this:

import pandas as pd
import matplotlib.pyplot as plt

d = {'cat1': [4, 6], 'cat2': [8, 5], 'cat3': [3, 2]}
gender = ['female', 'male']
df = pd.DataFrame(data=d, index=gender).T

df.plot.bar()
plt.show()

Which yields:

enter image description here

  • Related