matplotlib histogram: how to display the count over the bar?

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)