New in matplotlib 3.4.0
There is a new plt.bar_label
method to automatically label bar containers.
plt.hist
returns the bar container(s) as the third output:
data = np.random.default_rng(123).rayleigh(1, 70)
counts, edges, bars = plt.hist(data)
# ^
plt.bar_label(bars)
If you have a grouped or stacked histogram, bars
will contain multiple containers (one per group), so iterate:
fig, ax = plt.subplots()
counts, edges, bars = ax.hist([data, data * 0.3], histtype="barstacked")
for b in bars:
ax.bar_label(b)
Note that you can also access the bar container(s) via ax.containers
:
for c in ax.containers:
ax.bar_label(c)