What is matplotlib.pyplot.hist() in Python?

Histograms are used to represent data graphically in the form of adjacent bars. The x-axis represents the continuous data, while the y-axis represents the frequency that corresponds to that data.

There are multiple ways to plot histograms in Python. Matplotlib provides functions that make this process easier for the programmer.

Syntax

matplotlib.pyplot.hist(x, bins, range, density, weights,
cumulative, bottom, histtype, align, orientation, rwidth,
log, color, label, stacked, *, data, **kwargs)

Parameters

  1. x: A sequence of data. This parameter is required.
  2. bins: Can be an integer, a sequence, or string. (Optional)
  3. range: The specified lower and upper range of the bins. (Optional)
  4. density: A Boolean value. If set to True, the normalized counts will be returned as the first element of the tuple. (Optional)
  5. weights: A sequence of weights that has the same shape as x. (Optional)
  6. cumulative: A Boolean value. If set to True, the frequency of each bin is the sum of all previous frequencies. (Optional)
  7. bottom: An array or scalar that specifies the location of the bottom of each bin. (Optional)
  8. histtype: Specifies the type of histogram to plot. The default type is bar. Other options include barstacked, step, and stepfilled. (Optional)
  9. align: Specifies the horizontal alignment of the bars. Options are left, mid, and right. The default is mid. (Optional)
  10. orientation: Specifies the orientation of the histogram bars. Options are horizontal or vertical. The default is vertical. (Optional)
  11. rwidth: A float value that computes the width of the bars relative to the bin width. (Optional)
  12. log: A Boolean value that, if set to True, sets the axis to a log scale. (Optional)
  13. color: Specifies the colors of the bars. (Optional)
  14. label: A string that labels the dataset. (Optional)
  15. stacked: Boolean value that, if set to True, stacks datasets on top of each other. (Optional)

Return value

The function returns a tuple that contains the frequencies of the histogram bins, the edges of the bins, and the respective patches that create the histogram.

Code

#import libraries
from matplotlib import pyplot as plt
import numpy as np
#initialize a sequence of data
data = np.array([20,7,14,7,16,9,2,13,21,20,14,9,9,20,1])
#plot a histogram
plt.hist(data,
bins = 100,
density = 1,
color ='blue',
orientation='horizontal')
#set x and y labels
plt.xlabel('Counts')
plt.ylabel('Ages of students')
#show histogram
plt.show()

The code plots a histogram, as seen below, with color set to blue, orientation set to horizontal, number of bins set to 100, and density set to 1.

widget

Free Resources