NumPy – Histogram Using Matplotlib

NumPy - Histogram Using Matplotlib

In this chapter, we will discuss about NumPy – Histogram Using Matplotlib. This numPy has a numpy.histogram() function that is a graphical representation of the frequency distribution of data. Rectangles of equal horizontal size corresponding to class interval called bin and variable height corresponding to frequency.

The package is available in binary distribution as well as in the source code form on www.matplotlib.org.

NumPy – (histogram)Using Matplotlib

The numpy. histogram() function takes the input array and bins as two parameters. The successive elements in the bin array act as the boundary of each bin.

import numpy as np 
   
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) 
np.histogram(a,bins = [0,20,40,60,80,100]) 
hist,bins = np.histogram(a,bins = [0,20,40,60,80,100]) 
print hist 
print bins 

It will produce the following output −

[3 4 5 2 1]
[0 20 40 60 80 100]

plt()

Matplotlib can convert this numeric representation of a histogram into a graph. The plt() function of pyplot submodule takes the array containing the data and bin array as parameters and converts it into a histogram.

from matplotlib import pyplot as plt 
import numpy as np  
   
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) 
plt.hist(a, bins = [0,20,40,60,80,100]) 
plt.title("histogram") 
plt.show()

It should produce the following output −

Next Topic – Click Here

This Post Has 2 Comments

Leave a Reply