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

Plotting a stacked column containing a categorical list using Pandas

I have a Pandas dataframe with categorical data stored in a list. I would like to plot a stacked bar plot with col3 on the x-axis and col1 and col2 stacked on top of each other for the y-axis.

Reproducible dataframe structure:

    import pandas as pd
    import matplotlib.pyplot as plt

    d = {'col1': [1, 17, 40], 
         'col2': [10, 70, 2], 
         'col3': [['yellow', 'green', 'blue'], 
                  ['yellow', 'orange', 'blue'], 
                  ['blue', 'green', 'pink']]}
    df = pd.DataFrame(data=d)

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 :

Use:

df.explode('col3').set_index('col3').plot.bar(stacked=True)

Or:

df1 = (df.explode('col3')
        .melt('col3')
        .pivot_table(index='col3', columns='variable', values='value', aggfunc='sum'))

df1.plot.bar(stacked=True)
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