Reputation: 2331
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()
Upvotes: 0
Views: 2010
Reputation: 1041
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')
Upvotes: 3
Reputation: 4547
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()
Upvotes: -2