首页 > 解决方案 > 如何从熊猫数据框中绘制具有百分比分布的水平条形图?

问题描述

我有一个像这样的大熊猫数据框:

在:

d = {'type': ['type 1', 'type 2', 'type 2', 'type 3', 'type 1', 'type 4', 'type 5', 'type 6', 'type 6', 'type 7' ], 'value': ['yes', 'no', 'yes', 'no', 'yes', 'no', 'yes','no', 'yes', 'no']}
df = pd.DataFrame(data=d)
df

出去:

    type     value
0   type: 1   yes
1   type: 2   no
2   type: 2   yes
3   type: 3   no
4   type: 1   yes
5   type: 4   no
6   type: 5   yes
7   type: 6   no
8   type: 6   yes
9   type: 7   no

如何创建一个水平条形图,每个条形图中是/否值的百分比?到目前为止,我试图:

sns.barplot(x='type', y='value', data=df,  orient = 'h')

但是,对于每个是/否值,我只得到没有百分比分布的条形图。如何在不拆分的情况下将其绘制在同一个栏中?例如:

例子

在上面的示例中,yes/no 的总数位于 x 轴上。

标签: pythonpandasmatplotlibseaborn

解决方案


您可以使用pd.crosstab来计算百分比,然后plot.barh绘制条形图:

ax = (pd.crosstab(df['type'], df['value'], normalize='index')
        .plot.barh(stacked=True, alpha=0.8)
     )

输出:

在此处输入图像描述

有关条形图上的数字,请查看此问题


推荐阅读