Seaborn柱状图添加多标注 同时显示计数与对应百分比
问题场景
现有STRUD字段统计数据集,各结构类型对应的计数Struct_Count、占比Perc如下:
| STRUD | Struct_Count | Perc(单位:%) |
|---|---|---|
| Row | 1151 | 38.37 |
| Single | 865 | 28.83 |
| Detached | 447 | 14.90 |
| Row End | 384 | 12.80 |
| Multi | 146 | 4.87 |
| Inside | 3 | 0.10 |
| Missing | 2 | 0.07 |
| Default | 1 | 0.03 |
| Town End | 1 | 0.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
相关产品推荐
相关产品推荐

