简体   繁体   English

Seaborn 将百分比符号添加到条形图

[英]Seaborn add percentage sign to barplot

I am trying to add the percentage (%) sign to each value in my barplot but I am not entirely sure how to do it.我正在尝试将百分比 (%) 符号添加到我的条形图中的每个值,但我不完全确定该怎么做。 I know there is the get_text function that can help我知道有 get_text function 可以提供帮助

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 #annotate axis = seaborn axis

def annotateBars(row, ax=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')

plot = df.apply(annotateBars, ax=ax, axis=1)


Here这里

ax.annotate("%.0f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),

you are using string % data which is not specific to seaborn but is used in python in general.您使用的string % data并非特定于seaborn但通常在 python 中使用。 If you want to put literal % just double it ( %% ), for example:如果你想把文字%加倍( %% ),例如:

print("%.0f%%" % 95)

output output

95%

If you want to know more read old string formatting in docs如果您想了解更多信息,请阅读文档中的旧字符串格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM