Annotate bars with values on Pandas bar plots
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)
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.