For an array of values between 0 and 1, I want to create a histogram of 5 bins where bin one show the frequency(# of times) numbers between 0-0.2 show up in the array, bin 2 shows the frequency of numbers between 0.2-0.4, bin 3 is 0.4-0.6, bin 4: 0.6-0.8, bin 5 0.8-1.
import numpy as np
arr = np.array([0.5, 0.1, 0.05, 0.67, 0.8, 0.9, 1, 0.22, 0.25])
y, other_stuff = np.histogram(arr, bins=5)
x = range(0,5)
graph = plt.bar(x,height=y)
plt.show()
I think you are looking for matplotlib's hist
method.
With your sample array the code would look like:
import matplotlib.pyplot as plt
plt.hist(arr, bins=np.linspace(0,1,6), ec='black')
Is it what you are after ?
import numpy
from numpy.random import random
import matplotlib.pyplot as plt
arr = random(100)
y, other_stuff = numpy.histogram(arr, bins=5)
x = numpy.linspace(0.1, 0.9, 5)
graph = plt.bar(x, height=y, width=0.2, edgecolor='black')
plt.show()
As pointed out in the comment below, the snippet above does not define the edges of the bins in the call to histogram(). The one below corrects for that.
import numpy
import matplotlib.pyplot as plt
arr = numpy.array([0.5, 0.1, 0.05, 0.67, 0.8, 0.9, 1, 0.22, 0.25])
y, other_stuff = numpy.histogram(arr, bins=numpy.linspace(0, 1, 6))
graph = plt.bar(numpy.linspace(0.1, 0.9, 5), height=y, width=0.2,
edgecolor='black')
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.