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:
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:
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: