user12625679
user12625679

Reputation: 696

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

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)


Upvotes: 0

Views: 795

Answers (1)

Daweo
Daweo

Reputation: 36450

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. If you want to put literal % just double it (%%), for example:

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

output

95%

If you want to know more read old string formatting in docs

Upvotes: 1

Related Questions