Home > other >  Seaborn combining different data frames into one grouped bar plot
Seaborn combining different data frames into one grouped bar plot

Time:10-21

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

Can someone show me where I'm going wrong?

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

CodePudding user response:

You can plot your DataFrame with seaborn like below:

>>> import seaborn as sns
>>> sns.barplot(data=result, x='Area', y='Number', hue='Cat')

Or If you have DataFrame like in your question and you want to use enter image description here

  • Related