xuhdev
xuhdev

Reputation: 9333

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

With matplotlib's hist function, how can one make it display the count for each bin over the bar?

For example,

import matplotlib.pyplot as plt
data = [ ... ] # some data
plt.hist(data, bins=10)

How can we make the count in each bin display over its bar?

Upvotes: 40

Views: 69308

Answers (3)

tdy
tdy

Reputation: 41327

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)

Upvotes: 51

v.tralala
v.tralala

Reputation: 1685

Not solution solely using plt.hist() but with some added functionality.

If you don't want to specify your bins beforehand and only plot densities bars, but also want to display the bin counts you can use the following.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randn(100)
density, bins, _ = plt.hist(data, density=True, bins=20)
count, _ = np.histogram(data, bins)
for x,y,num in zip(bins, density, count):
    if num != 0:
        plt.text(x, y+0.05, num, fontsize=10, rotation=-90) # x,y,str

The result looks as follows:

enter image description here

Upvotes: 12

kiviak
kiviak

Reputation: 1103

it seems hist can't do this,you can write some like :

your_bins=20
data=[]
arr=plt.hist(data,bins=your_bins)
for i in range(your_bins):
    plt.text(arr[1][i],arr[0][i],str(arr[0][i]))

Upvotes: 27

Related Questions