Wednesday, December 25, 2024
Google search engine
HomeLanguagesMatplotlib.pyplot.hist() in Python

Matplotlib.pyplot.hist() in Python

Matplotlib is a library in Python and it is a numerical-mathematical extension for the NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.

Matplotlib Histogram

A histogram is used to represent data provided in the form of some groups. It is an accurate method for the graphical representation of numerical data distribution. It is a type of bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency. Python’s Matplotlib Library provides us with an easy way to create Histograms using Pyplot.

Matplotlib pyplot.hist() Syntax

In Python hist() function in the pyplot of the Matplotlib library is used to plot a histogram.

Syntax: matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype=’bar’, align=’mid’, orientation=’vertical’, rwidth=None, log=False, color=None, label=None, stacked=False, \*, data=None, \*\*kwargs) 

Parameters: This method accept the following parameters that are described below:

  • x : This parameter are the sequence of data.
  • bins : This parameter is an optional parameter and it contains the integer or sequence or string.
  • range : This parameter is an optional parameter and it the lower and upper range of the bins.
  • density : This parameter is an optional parameter and it contains the boolean values.
  • weights : This parameter is an optional parameter and it is an array of weights, of the same shape as x.
  • bottom : This parameter is the location of the bottom baseline of each bin.
  • histtype : This parameter is an optional parameter and it is used to draw type of histogram. {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}
  • align : This parameter is an optional parameter and it controls how the histogram is plotted. {‘left’, ‘mid’, ‘right’}
  • rwidth : This parameter is an optional parameter and it is a relative width of the bars as a fraction of the bin width
  • log : This parameter is an optional parameter and it is used to set histogram axis to a log scale
  • color : This parameter is an optional parameter and it is a color spec or sequence of color specs, one per dataset.
  • label : This parameter is an optional parameter and it is a string, or sequence of strings to match multiple datasets.
  • normed : This parameter is an optional parameter and it contains the boolean values.It uses the density keyword argument instead.

Returns: This returns the following

  • n :This returns the values of the histogram bins.
  • bins :This returns the edges of the bins.
  • patches :This returns the list of individual patches used to create the histogram.

Create a Histogram in Matplotlib

Using the Matplotlib library in Python, we can create many types of histograms. Let us see a few examples to better understand the functionality of hist() function.

Example 1:

In this example, we will create a simple histogram using the hist() function with the default parameters. The term ‘default parameters’ means that we will only pass the data as the parameters to the hist() function in Matplotlib, all the other parameters will get a default value.

Python3




# import module
import matplotlib.pyplot as plt
 
# create data
data = [32, 96, 45, 67, 76, 28, 79, 62, 43, 81, 70,
        61, 95, 44, 60, 69, 71, 23, 69, 54, 76, 67,
        82, 97, 26, 34, 18, 16, 59, 88, 29, 30, 66,
        23, 65, 72, 20, 78, 49, 73, 62, 87, 37, 68,
        81, 80, 77, 92, 81, 52, 43, 68, 71, 86]
 
# create histogram
plt.hist(data)
 
# display histogram
plt.show()


Output:

Histogram with hist() with default parameters

Example 2: 

In this example, we will create a histogram using the hist() function in Matplotlib and pass the necessary parameters such as bins, color, density, etc. We also used pyplot.plot() function to plot a dashed line on the graph.

Python3




# Implementation of matplotlib function
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
  
np.random.seed(10**7)
mu = 121
sigma = 21
x = mu + sigma * np.random.randn(1000)
  
num_bins = 100
  
n, bins, patches = plt.hist(x, num_bins,
                            density = 1,
                            color ='green',
                            alpha = 0.7)
  
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
     np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
 
plt.plot(bins, y, '--', color ='black')
 
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
 
plt.title('matplotlib.pyplot.hist() function Example\n\n',
          fontweight = "bold")
 
plt.show()


Output:

A simple histogram using matplotlib.pyplot.hist() function

A simple histogram using matplotlib.pyplot.hist() function

Example 3: 

In this example, we will create a histogram with different attributes using matplotlib.pyplot.hist() function. We define a specific set of colors for the bars of the histogram bars

Python3




# Implementation of matplotlib function
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
   
np.random.seed(10**7)
n_bins = 20
x = np.random.randn(10000, 3)
   
colors = ['green', 'blue', 'lime']
 
plt.hist(x, n_bins, density = True,
         histtype ='bar',
         color = colors,
         label = colors)
 
plt.legend(prop ={'size': 10})
 
plt.title('matplotlib.pyplot.hist() function Example\n\n',
          fontweight = "bold")
 
plt.show()


Output:

A histogram using matplotlib.pyplot.hist() function

A histogram using matplotlib.pyplot.hist() function

RELATED ARTICLES

Most Popular

Recent Comments