.histogram()
Published Apr 29, 2025
Contribute to Docs
The .histogram()
function in NumPy is used to compute the frequency distribution of data by dividing values into bins and counting how many fall into each bin. It’s commonly used in data analysis, statistical modeling, and visualization to understand the distribution of numerical data.
Syntax
numpy.histogram(a, bins=10, range=None, density=None, weights=None)
Parameters:
a
(array_like): Input data. The histogram is computed over the flattened array.bins
(int
, sequence of scalars, orstr
, optional):- If an
int
, it defines the number of equal-width bins (default is10
). - If a sequence, it specifies the bin edges.
- If a str, it defines the method used to calculate the optimal bin width.
- If an
range
(tuple, optional): Lower and upper range of the bins. Defaults to(a.min(), a.max())
.density
(bool
, optional):- If
False
, returns the count of samples in each bin. - If
True
, returns the probability density function.
- If
weights
(array_like, optional): Weights for each value ina
. Ifdensity=True
, weights are normalized.
Return value:
The .histogram()
function in NumPy returns a tuple of two arrays:
(hist, bin_edges)
hist
: A NumPy array of counts or probability densities (depending on thedensity
parameter). It tells you how many elements from the input fell into each bin.bin_edges
: A NumPy array of bin edge values. It has one more element thanhist
, representing the edges of the bins, including the rightmost edge.
Example
This example demonstrates the use of .histogram()
in NumPy:
import numpy as np# Creating a NumPy histogram from array and set binsa = np.histogram([1, 2, 1, 3, 2, 4, 3, 0, 0, 5], bins=[0, 1, 2, 3, 4, 5, 6])# Print the histogramprint(str(1) + ':' + str(a))# Creating a NumPy histogram with numpy.arange() and setting density as Trueb = np.histogram(np.arange(4), bins=np.arange(5), density=True)# Print the histogramprint(str(2) + ':' + str(b))
The output for the example will be:
1:(array([2, 2, 2, 2, 1, 1]), array([0, 1, 2, 3, 4, 5, 6]))2:(array([0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4]))
Codebyte Example
This codebyte example shows the use of NumPy .histogram()
to display an array in a histogram display:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours