如何为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
相关产品推荐
相关产品推荐

