Side by Side BarPlot

故事扮演 提交于 2020-03-05 04:41:49

问题


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

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


回答1:


Use melt on your dateframe then plot it with seaborn.

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")

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

import seaborn as sns
import matplotlib.pyplot as plt
fig = plt.figure()
sns.factorplot(x = 'investors', y='value', hue = 'investments',data=dfs1, kind='bar')
plt.show()

output:



来源:https://stackoverflow.com/questions/52028043/side-by-side-barplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!