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
- This can be accomplished more succinctly by using
.bar_label()
- This annotation requires a custom label, so use the
labels
parameter - Bar Label Demo
- This annotation requires a custom label, so use the
- The
labels
list comprehension uses an assignment expression (:=
), which requirespython >= 3.8
.
def autolabel(rects, axes):
labels = [f'{w} ({int(round(w/102*100))}%)' for rect in rects if (w := rect.get_width()) is not None]
axes.bar_label(rects, labels=labels, label_type='edge', fontsize=8, padding=3)
matplotlib < 3.4.2
rect.get_y() + rect.get_height() / 2
see thatrect.get_height()
needs to be divided by 2.- Change to
va='center_baseline'
and addfontsize=8
def autolabel(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])
Post a Comment for "How To Align Annotations At The End Of A Horizontal Bar Plot"