Compute the histogram of a set of data using NumPy in Python
Numpy provides us the feature to compute the Histogram for the given data set using NumPy.histogram() function. The formation of histogram depends on the data set, whether it is predefined or randomly generated.
Syntax : numpy.histogram(data, bins=10, range=None, normed=None, weights=None, density=None)
Case 1: Computing the Numpy Histogram with the help of Random Data set
Python3
# import Numpy and matplotlibfrom matplotlib import pyplot as pltimport numpy as np # Creating random datasetdata_set = np.random.randint(100, size=(50)) # Creation of plotfig = plt.figure(figsize=(10, 6)) # plotting the Histogram with certain intervalsplt.hist(data_set, bins=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) # Giving title to Histogramplt.title("Random Histogram") # Displaying Histogramplt.show() |
Output:

In the above example, we created a random data set using np.random.randint() and plot the Numpy Histogram
Case 2: Computing the Numpy Histogram with the help of Pre-defined Data set
Python3
# import Numpy and matplotlibfrom matplotlib import pyplot as pltimport numpy as np # Using predefined datasetdata_set = [45, 85, 95, 10, 58, 77, 92, 72, 52, 22, 32, 5, 95, 2, 23, 24, 50, 40, 60, 69, 44, 80, 21, 15, 17, 55, 21, 88] # Creation of plotfig = plt.figure(figsize=(10, 5)) # plotting the Histogram with certain intervalsplt.hist(data_set, bins=[0, 15, 30, 45, 60, 75, 90, 105]) # Giving title to Histogramplt.title("Predefined Histogram") # Displaying Histogramplt.show() |

In the above example, we take a predefined data set and plot the Numpy Histogram.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


