Skip to content Skip to sidebar Skip to footer

How To Align Annotations At The End Of A Horizontal Bar Plot

I'm trying to correctly align the numbers and percentages in the barplots I'm making so that they're exactly after each bar, but having some troubles trying to do so. I want the: '

Solution 1:

matplotlib >= 3.4.2

defautolabel(rects, axes):
    labels = [f'{w} ({int(round(w/102*100))}%)'for rect in rects if (w := rect.get_width()) isnotNone]
    axes.bar_label(rects, labels=labels, label_type='edge', fontsize=8, padding=3)

enter image description here

matplotlib < 3.4.2

  • rect.get_y() + rect.get_height() / 2 see that rect.get_height() needs to be divided by 2.
  • Change to va='center_baseline' and add fontsize=8
defautolabel(rects, axes):
    for rect in rects:
        width = rect.get_width()
        perc=int(round(width/102*100))
        axes.annotate(f'{width} ({perc}%)',
                      xy=(width, rect.get_y() + rect.get_height() / 2), 
                      xytext=(0, 0),
                      textcoords="offset points",
                      ha='left', va='center_baseline', fontsize=8)


autolabel(rects1, axes[0])
autolabel(rects2, axes[0])

enter image description here

Post a Comment for "How To Align Annotations At The End Of A Horizontal Bar Plot"