并排柱形图

9
我将尝试使用seabornpandas创建这种“并排”的条形图。

enter image description here

以下是我创建数据框的方式:

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

以下是条形图的代码:

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

有人可以帮忙吗?谢谢


1
你看过这个教程吗?https://jakevdp.github.io/PythonDataScienceHandbook/04.14-visualization-with-seaborn.html - Stanley
1个回答

12

使用 melt 函数对数据框进行重塑,然后使用 seaborn 绘图。

更新:在较新版本的 seaborn 中,factorplot 已更改为 catplot。

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

输出:

条形图


1
“investments”这个列标题是从哪里来的? - Brandon Kuczenski
1
@BrandonKuczenski 我在 pd.melt 后将列名 "variable" 重命名为 "investments",但我忘记在答案中包含它。现在我已经在答案中添加了重命名步骤。谢谢你的注意并让我知道。抱歉回复晚了,我有一段时间没有使用 SO。 - Abhi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接