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

Seaborn柱状图添加多标注 同时显示计数与对应百分比

问题场景

现有STRUD字段统计数据集,各结构类型对应的计数Struct_Count、占比Perc如下:

STRUDStruct_CountPerc(单位:%)
Row115138.37
Single86528.83
Detached44714.90
Row End38412.80
Multi1464.87
Inside30.10
Missing20.07
Default10.03
Town End10.03

当前使用如下seaborn代码绘制柱状图,已经实现柱体上标注Struct_Count计数值,需要额外标注对应Perc百分比:

plt.figure(figsize=(15, 8))
 
plots = sns.barplot(x="STRUD", y="Struct_Count", data=df2)
 
for bar in plots.patches:  
    plots.annotate(format(bar.get_height(), '.0f'),
                   (bar.get_x() + bar.get_width() / 2,
                    bar.get_height()), ha='center', va='center',
                   size=13, xytext=(0, 5),
                   textcoords='offset points')
    
plt.title("Distribution of STRUCT")
plt.show()
实现方案

seaborn的barplot绘制柱体的顺序和传入的DataFrame行顺序完全对应,遍历柱体时按索引匹配对应行的百分比值,把计数和百分比拼接成标注文本即可,修改后的完整代码如下:

plt.figure(figsize=(15, 8))
plots = sns.barplot(x="STRUD", y="Struct_Count", data=df2)
 
for idx, bar in enumerate(plots.patches):
    # 获取当前柱体的计数值
    count_val = int(bar.get_height())
    # 按索引匹配当前柱体对应的百分比值
    perc_val = df2.iloc[idx]["Perc"]
    # 拼接标注文本,用换行分隔计数和百分比
    annot_label = f"{count_val}\n{perc_val}%"
    plots.annotate(annot_label,
                   (bar.get_x() + bar.get_width() / 2, bar.get_height()),
                   ha='center', va='center',
                   size=13, xytext=(0, 10), # 适当增大纵向偏移,避免两行文本贴在柱顶
                   textcoords='offset points')
    
plt.title("Distribution of STRUCT")
plt.show()
  • 注意:如果绘图前对df2做过排序、过滤等操作,要保证传入barplot的数据源和遍历取数用的df2行顺序完全一致,否则会出现标注错位。
  • 可根据显示效果调整xytext的第二个参数(纵向偏移量),数值越大标注离柱顶越远。
  • 如果需要调整百分比的小数位数,修改格式化逻辑即可,比如保留1位小数可写为f"{perc_val:.1f}%"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 09:27:34