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

Stacked bar chart for a pandas df

I have a df like this and would like to plot stacked bar chart where in the x axis is Component and the y-axis shows the count by ‘Major’, ‘Minor’ etc.

       Component Priority
0  Browse Groups    Minor
1  Notifications    Major
2             BI    Major
3             BI    Minor
4             BI    Minor

For example, the first bar would have 1st component with a count of 1 minor,..so on.. and 3rd would have ‘BI’ in x-axis with 1 count of Major and 2 counts of Minor stacked.
What is the simplest way to do this in seaborn or something similar?

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

>Solution :

You can groupby both columns and count on Priority, then unstack and plot as stacked bar chart:

df.groupby(['Component', 'Priority']).Priority.count().unstack().plot.bar(stacked=True)

Example:

import pandas as pd

df = pd.DataFrame({'Component': list('abccc'), 'Priority': ['Minor', 'Major', 'Major', 'Minor', 'Minor']})
df.groupby(['Component', 'Priority']).Priority.count().unstack().plot.bar(stacked=True)

enter image description here

As an alternative, you can use a crosstab:

pd.crosstab(df.Component, df.Priority).plot.bar(stacked=True)

If you want to use seaborn (I only now saw the seaborn tag), you can use a displot:

import seaborn as sns

sns.displot(x='Component', hue='Priority', data=df, multiple='stack')

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