【问题标题】:Annotate stacked barplot matplotlib and pandas [duplicate]注释堆叠的 barplot matplotlib 和 pandas [重复]
【发布时间】:2018-10-14 02:33:47
【问题描述】:

我有一个存储调查结果的简单数据框。列是:

| Age | Income | Satisfaction |

它们都包含15(分类)之间的值。我设法生成了一个堆叠条形图,显示了 Satisfaction 值在不同年龄的人之间的分布。 代码是:

#create a random df
data = []
for i in range(500):
    sample = {"age" : random.randint(0,5), "income" : random.randint(1,5), "satisfaction" : random.randint(1,5)}
data.append(sample)
df = pd.DataFrame(data)
#group by age
counter = df.groupby('age')['satisfaction'].value_counts().unstack()
#calculate the % for each age group 
percentage_dist = 100 * counter.divide(counter.sum(axis = 1), axis = 0)
percentage_dist.plot.bar(stacked=True)

这会生成以下所需的图:

但是,如果Age-0green 子集(百分比)高于Age-2 中的子集,则很难进行比较。因此,有没有办法在条形图的每个子部分的顶部添加百分比。像这样的东西,但对于每一个酒吧:

【问题讨论】:

    标签: python pandas matplotlib bar-chart


    【解决方案1】:

    一种选择是迭代补丁以获得它们的宽度、高度和左下角坐标,并使用这些值将标签放置在相应条的中心。

    为此,必须存储 pandas bar 方法返回的坐标区。

    ax = percentage_dist.plot.bar(stacked=True)
    for p in ax.patches:
        width, height = p.get_width(), p.get_height()
        x, y = p.get_xy() 
        ax.text(x+width/2, 
                y+height/2, 
                '{:.0f} %'.format(height), 
                horizontalalignment='center', 
                verticalalignment='center')
    

    这里,注释值设置为 0 位小数,但这可以很容易地修改。

    使用此代码生成的输出图如下:

    【讨论】:

    • 这对我来说是最好的答案,包括链接的帖子。我补充说:if height==0: continue 用于堆栈中没有出现类别的情况(这会在底部给出异常的 0% 标签)。
    • 很高兴能帮上忙!我实际上并没有过多考虑这个答案,我已经编辑以改进标签放置,现在它们居中。
    • 您也可以将数字的格式更改为{:.0%}
    • 使用这种方法,当每列的高度不同时,你将如何计算百分比(列补丁不加到 100 - 不代表百分比)
    • 我可以通过枚举补丁然后使用索引来索引类别来做到这一点。但是,这感觉不干净...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多