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?
To display the count over the bar in matplotlib histogram, we can iterate each patch and use text() method to place the values over the patches.
Use the syntax “for index, value in enumerate(iterable)” with iterable as the list of bar values to access each index, value pair in iterable. At each iteration, call matplotlib. pyplot. text(x, y, s) with x as value, y as index, and s as str(value) to label each bar with its size.
We can extract Frequency Counts of Histogram using hist() Function in R programming language. hist() function is used to plot a histogram out of the given data.
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]))
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With