7

I'm trying to create this kind of "side by side" barplot with seaborn and pandas.

enter image description here

this is how I create data frame:

dfs = pd.DataFrame(data={'investors': ['first','second','third'], 'stocks': [23, 123, 54], 'bonds': [54, 67, 123], 'real estate': [45, 243, 23]})

And here is barplot code:

sns.factorplot(x='investors', y='bonds', data=dfs, kind='bar')

Can anyone please help? Thanks

Vladimir Chernenko
  • 423
  • 2
  • 6
  • 10
  • 1
    have you taken a look at this tutorial? https://jakevdp.github.io/PythonDataScienceHandbook/04.14-visualization-with-seaborn.html – Stanley Aug 26 '18 at 16:27

1 Answers1

12

Use melt on your dateframe then plot it with seaborn.

update: factorplot was changed to catplot in newer versions of seaborn.

sns.catplot(x = 'investors', y='value', 
            hue = 'investments',data=dfs1, 
            kind='bar')

# import libraries
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

dfs = pd.DataFrame(data={'investors': ['first','second','third'], 
                         'stocks': [23, 123, 54], 
                         'bonds': [54, 67, 123], 
                         'real estate': [45, 243, 23]})

dfs1 = pd.melt(dfs, id_vars = "investors")
dfs1 = dfs1.rename(columns={"variable": "investments"})

print(dfs1)

    investors    investments    value
0   first         stocks         23
1   second        stocks        123
2   third         stocks         54
3   first          bonds         54
4   second         bonds         67
5   third          bonds        123
6   first      real estate       45
7   second     real estate      243
8   third      real estate       23


sns.factorplot(x = 'investors', y='value', 
               hue = 'investments',data=dfs1, kind='bar')
plt.show()

output :-

barplot

Abhi
  • 4,068
  • 1
  • 16
  • 29
  • 1
    where does the column heading "investments" come from? – Brandon Kuczenski Mar 30 '22 at 06:17
  • 1
    @BrandonKuczenski I have renamed the column "variable" after the `pd.melt` to "investments" and I had forgot to include it in the answer. I have added the rename step in the answer now. Thank you for noticing and letting me know. Sorry for the late response, I haven't used SO in a while. – Abhi Nov 16 '22 at 18:09