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)
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]))