Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Plot DataFrame with Strings into stacked bar chart

following situation:

I have a dataframe (df) with the following scheme:

Gender AgeGroup
0 m Group1
1 m Group2
2 f Group2
3 f Group1

I want to do a stacked bar chart using pandas & matplotlib, with the age groups on the x axis and the amount of genders on a stacked bar on the y-axis.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried plotting it with various:

df.plot.bar(column=["AgeGroup", "Gender"], stacked=True)

But I always get the error that there are no numeric values inside the dataframe, which makes sense, but I am trying to count those.

What would the ideal solution be here?

Thanks!

>Solution :

Use a crosstab:

pd.crosstab(df['AgeGroup'], df['Gender']).plot.bar(stacked=True)

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading