【问题标题】:How to plot an horizontal barplot with percentage distribution from a pandas dataframe?如何从熊猫数据框中绘制具有百分比分布的水平条形图?
【发布时间】:2020-11-26 22:17:43
【问题描述】:

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

在:

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 轴上。

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

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

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

    输出:

    有关条形图上的数字,请查看this question

    【讨论】:

    • 有没有办法在栏的顶部放置一个百分比标签?
    • ax.text 中使用x, y,例如ax.text(x/2, y+barheight...
    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    相关资源
    最近更新 更多