Annotate bars with values on Pandas bar plots
You get it directly from the axes' patches:
for p in ax.patches: ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))
You'll want to tweak the string formatting and the offsets to get things centered, maybe use the width from p.get_width()
, but that should get you started. It may not work with stacked bar plots unless you track the offsets somewhere.
Solution which also handles the negative values with sample float formatting.
Still needs tweaking offsets.
df=pd.DataFrame({'A':np.random.rand(2)-1,'B':np.random.rand(2)},index=['val1','val2'] )ax = df.plot(kind='bar', color=['r','b']) x_offset = -0.03y_offset = 0.02for p in ax.patches: b = p.get_bbox() val = "{:+.2f}".format(b.y1 + b.y0) ax.annotate(val, ((b.x0 + b.x1)/2 + x_offset, b.y1 + y_offset))
As of matplotlib 3.4.0:
A new
Axes.bar_label
helper method has been added for auto-labeling bar charts.
For single-group bar charts, supply ax.containers[0]
:
df = pd.DataFrame({'A': np.random.rand(2)}, index=['value1', 'value2'])ax = df.plot.barh()ax.bar_label(ax.containers[0])
For multi-group bar charts, iterate ax.containers
:
df = pd.DataFrame({'A': np.random.rand(2), 'B': np.random.rand(2)}, index=['value1', 'value2'])ax = df.plot.bar()for container in ax.containers: ax.bar_label(container)
See matplotlib's bar label demos for comprehensive examples using the optional styling params:
Axes.bar_label(self, container, labels=None, *, fmt='%g', label_type='edge', padding=0, **kwargs)