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

如何为Seaborn绘制的barplot柱状图标注数值添加百分号(%)标识

Seaborn柱状图标注追加百分号解决方案

你只需要修改annotate方法里的文本格式化规则即可,Python格式化字符串中如果要输出原生百分号,需要连续写两个%进行转义。

调整后的完整代码

import seaborn as sns

g =  sns.catplot(
    data=df, 
    kind="bar",
    x="City", 
    y="Customers", 
    hue="Acquisition_Channel",
    ci="sd", 
    palette="dark", 
    alpha=.7,
    height=8,   
 )

g.set(ylim=(0, 100)) 
g.despine(right=False) 
g.set_xlabels("City") 
g.set_ylabels("Share of Customers vs. Total acquired Customers (%)")  
g.set_yticklabels("") 

ax = g.ax 

def annotateBars(ax):
    for p in ax.patches:
        # 仅修改此处格式化字符串,添加转义后的百分号
        ax.annotate("%.0f%%" % p.get_height(), 
                    (p.get_x() + p.get_width() / 2., p.get_height()),
                    ha='center', va='center', fontsize=12, color='gray', 
                    rotation=0, xytext=(0, 20),
                    textcoords='offset points')

# 原代码用df.apply遍历属于冗余操作,直接调用函数即可完成所有柱体标注
annotateBars(ax)

补充说明

  • 如果你的Customers字段存储的是小数比例(比如0.25对应25%),可以把格式化逻辑改成"%.0f%%" % (p.get_height()*100)即可自动换算为百分比数值再加标识
  • 可以根据标注显示效果调整xytext参数的第二个数值,避免标注超出画布或者被柱体遮挡

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 17:54:05