You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python堆叠柱状图中添加计数标签的实现方法

在堆叠百分比柱状图中添加原始count数值

我用Python的pandas绘制了堆叠百分比柱状图,目前图表只显示百分比数据,想在每个堆叠色块内部显示对应的原始count数值(比如右侧bar中Email对应的24225),请问该怎么实现?现有代码如下:

import pandas as pd

# sample data
data = {'fields': ['LastName', 'Race', 'Email', 'MidName', 'StreetAddress', 'Phone', 'State', 
    'FirstName', 'Gender', 'Expiration', 'StreetAddress'],
    'Status': ['complete', 'missing', 'missing', 'complete', 'complete', 'missing', 'missing', 
    'complete', 'complete', 'complete', 'missing'],
    'count': [27399, 146, 24225, 26078, 27269, 59, 28, 27399, 27403, 14017, 134]}

df = pd.DataFrame(data)

# pivot the dataframe into the wide form
dfp = df.pivot(index='Status', columns='fields', values='count')

# get the totals along the rows
tot = dfp.sum(axis=1)

# calculate percent
per = dfp.div(tot, axis=0).mul(100).round(2)

# plot
ax = per.plot(kind='bar', stacked=True, figsize=(8, 6), rot=0)
ax.legend(bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)

解决方案

你可以在绘制完柱状图后,遍历每个堆叠的条形元素,结合原始的dfp数据(存储count值),在每个色块的中心位置添加对应的数值标签。修改后的完整代码如下:

import pandas as pd

# sample data
data = {'fields': ['LastName', 'Race', 'Email', 'MidName', 'StreetAddress', 'Phone', 'State', 
    'FirstName', 'Gender', 'Expiration', 'StreetAddress'],
    'Status': ['complete', 'missing', 'missing', 'complete', 'complete', 'missing', 'missing', 
    'complete', 'complete', 'complete', 'missing'],
    'count': [27399, 146, 24225, 26078, 27269, 59, 28, 27399, 27403, 14017, 134]}

df = pd.DataFrame(data)

# pivot the dataframe into the wide form
dfp = df.pivot(index='Status', columns='fields', values='count')

# get the totals along the rows
tot = dfp.sum(axis=1)

# calculate percent
per = dfp.div(tot, axis=0).mul(100).round(2)

# plot
ax = per.plot(kind='bar', stacked=True, figsize=(8, 6), rot=0)
ax.legend(bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)

# 添加原始count数值标签
for i, status in enumerate(dfp.index):
    # 遍历每个堆叠的条形组
    for container in ax.containers:
        # 遍历组内的每个条形
        for bar in container:
            # 获取当前条形对应的fields名称
            field = bar.get_label()
            # 从dfp中取出对应的count值
            count_val = dfp.loc[status, field]
            # 计算标签的位置(条形中心)
            x = bar.get_x() + bar.get_width() / 2
            y = bar.get_y() + bar.get_height() / 2
            # 添加文本标签,设置字体大小避免重叠
            ax.text(x, y, str(count_val), ha='center', va='center', fontsize=8)

关键说明

  • 原始的dfp数据框保存了每个Status和fields组合的count数值,这是我们需要显示的内容
  • 通过ax.containers获取所有堆叠的条形组,逐个遍历每个条形元素
  • 利用bar.get_label()匹配对应的fields,结合当前的Status行,从dfp中提取对应count值
  • 使用ax.text()将数值放置在条形的中心位置,通过ha='center'和va='center'确保对齐

内容的提问来源于stack exchange,提问作者vanetoj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 04:15:37