Home > other >  How to combine different DataFrames into one grouped bar plot
How to combine different DataFrames into one grouped bar plot

Time:10-22

I'm trying to copy the answer from enter image description here

Can someone show me where I'm going wrong?

CodePudding user response:

  • You can plot your long DataFrame with seaborn
>>> import seaborn as sns
>>> sns.barplot(data=result, x='Area', y='Number', hue='Cat')
  • If you have long DataFrame, like in the OP, use pivot_table to create a wide DataFrame, and then plot with enter image description here

    CodePudding user response:

    It's difficult to give a great answer because I know this is just demo data so dealing with your real data is going to be different. I think the way you are creating the dataframe is giving you the problem since you are plotting directly with pandas.

    Currently, your dataframe looks like:

    enter image description here

    ...but you need your X axis to be the index, and a separate column for Cat1 and Cat2 with their respective values. Something closer to:

    enter image description here

    The way you accomplish this will depend on your actual dataset, but using the example provided (I slightly changed your input values for better visualization), this was my approach:

    import pandas as pd
    
    cat1 = {'item1':4, 'item2':6, 'item3':7,'item4':8,'item5':10}
    cat2 = {'item1':5, 'item2':4, 'item3':12,'item4':6,'item5':3}
    
    df1 = pd.DataFrame.from_dict(cat1, orient='index', columns=['Cat1'])
    df2 = pd.DataFrame.from_dict(cat2, orient='index', columns=['Cat2'])
    
    df = pd.concat([df1, df2], axis=1)
    
    ax = df.plot.bar(rot=0)
    

    Output:

    enter image description here

  • Related