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

如何将堆叠条形图转换为带有百分比标签的堆叠百分比条形图

把堆叠条形图改成带百分比标签的堆叠百分比条形图

嘿,我来帮你调整代码,把普通堆叠条形图改成带百分比标签的堆叠百分比图!咱们一步步来修改:

首先,核心思路是把原有的计数数据转换成每行的百分比,然后给每个堆叠区块加上对应的百分比标签。下面是修改后的完整代码:

import pandas as pd
import matplotlib.pyplot as plt

# 读取数据
df_responses= pd.read_csv('https://raw.githubusercontent.com/eng-aomar/Security_in_practice/main/secuirtyInPractice.csv')
df_new = df_responses.iloc[:,9:21]

# 初始化空 dataframe,统计各列分类的计数
df2 = pd.DataFrame()
for col in df_new:
    grped = df_new.groupby(col).size()
    grped = grped.rename(grped.index.name)
    df2 = df2.merge(grped.to_frame(), how='outer', left_index=True, right_index=True)

# 将计数转换为百分比:每行的每个值除以该行总和,再乘以100
df2_percent = df2.div(df2.sum(axis=1), axis=0) * 100

# 绘制堆叠百分比条形图
ax = df2_percent.plot.bar(stacked=True, figsize=(12, 6))
plt.title('堆叠百分比条形图', fontsize=14)
plt.ylabel('百分比 (%)', fontsize=12)
plt.xlabel('分类', fontsize=12)

# 给每个堆叠区块添加百分比标签
for p in ax.patches:
    width, height = p.get_width(), p.get_height()
    if height > 0:  # 只显示有数值的标签(避免0值的空标签)
        x, y = p.get_xy()
        ax.text(x + width/2, 
                y + height/2, 
                f'{height:.1f}%',  # 保留1位小数的百分比
                ha='center', 
                va='center',
                fontsize=10)

plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')  # 把图例挪到图外面,避免遮挡
plt.tight_layout()
plt.show()

关键修改点说明:

  • 百分比转换:用df2.div(df2.sum(axis=1), axis=0) * 100实现每行数据的占比计算,axis=1表示按行求和,axis=0保证每行的每个值除以该行的总和。
  • 标签添加:遍历绘图后的每个色块(ax.patches),计算色块的中心位置,然后添加格式化的百分比文本,ha='center'和va='center'确保标签居中显示。
  • 优化显示:调整了图的大小、图例位置,避免遮挡,同时只显示有数值的标签(过滤掉0值的情况)。

这样修改后,你就能得到一个清晰的堆叠百分比条形图,每个部分都标注了对应的占比啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:52:48