pythonmatplotlibbar-chart

How to add % to annotations using the fmt option of bar_label


I'm trying to use the new bar_label option in Matplotlib but am unable to find a way to append text e.g. '%' after the label values. Previously, using ax.text I could use f-strings, but I can't find a way to use f-strings with the bar-label approach.

fig, ax = plt.subplots(1, 1, figsize=(12,8))
hbars = ax.barh(wash_needs.index, wash_needs.values, color='#2a87c8')
ax.tick_params(axis='x', rotation=0)

# previously I used this approach to add labels 
#for i, v in enumerate(wash_needs):
#    ax.text(v +3, i, str(f"{v/temp:.0%}"), color='black', ha='right', va='center')

ax.bar_label(hbars, fmt='%.2f', padding=3) # this adds a label but I can't find a way to append a '%' after the number
    
plt.show()

Solution

  • I found a way to append '%' to the label figures - add an additional '%%'

    ax.bar_label(hbars, fmt='%.2f%%', padding=3)
    

    Working Example

    import pandas as pd
    import seaborn as sns  # for tips data
    
    tips = sns.load_dataset('tips').loc[:15, ['total_bill', 'tip']]
    tips.insert(2, 'tip_percent', tips.tip.div(tips.total_bill).mul(100).round(2))
    
       total_bill   tip  tip_percent
    0       16.99  1.01         5.94
    1       10.34  1.66        16.05
    2       21.01  3.50        16.66
    3       23.68  3.31        13.98
    4       24.59  3.61        14.68
    
    # plot
    ax = tips.plot(kind='barh', y='tip_percent', legend=False, figsize=(12, 8))
    labels = ax.set(xlabel='Tips: Percent of Bill (%)', ylabel='Record', title='Tips % Demo')
    annotations = ax.bar_label(ax.containers[0], fmt='%.2f%%', padding=3)
    ax.margins(x=0.1)
    

    enter image description here