Skip to content

NumPy - Histogram Using Matplotlib

NumPy - Creating Histograms with Matplotlib

Section titled “NumPy - Creating Histograms with Matplotlib”

A histogram is a graphical representation of the distribution of numerical data. It groups data points into specified ranges called ‘bins’ and plots the frequency (count) of data points falling into each bin, usually as bars.

NumPy provides the numpy.histogram() function to compute the histogram data (frequencies and bin edges) without actually plotting it. This is useful if you need the raw counts for further analysis.

It takes the input data array and the desired bins as primary arguments. Bins can be specified either as an integer (number of equal-width bins) or as a sequence of bin edges.

import numpy as np
# Sample data
a = np.array([22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27])
# Define bin edges explicitly
bin_edges = [0, 20, 40, 60, 80, 100]
# Compute the histogram
# Returns the counts (hist) and the bin edges (bins)
hist, bins = np.histogram(a, bins=bin_edges)
print("Frequency counts per bin:")
print(hist)
print("\nBin edges:")
print(bins)

Output:

Frequency counts per bin:
[4 3 5 2 1]
Bin edges:
[ 0 20 40 60 80 100]

Explanation: The output hist [4 3 5 2 1] means: 4 values fall between 0 and 20 (exclusive of 20), 3 values fall between 20 and 40, 5 values between 40 and 60, 2 values between 60 and 80, and 1 value between 80 and 100. The bins output confirms the edges used.

While np.histogram() computes the data, matplotlib.pyplot.hist() (often imported as plt.hist()) both computes (if necessary) and plots the histogram directly.

plt.hist() takes the data array and bin information (similar to np.histogram) as input and generates the visual plot.

import matplotlib.pyplot as plt
import numpy as np
# Sample data (same as before)
a = np.array([22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27])
# Define bin edges
bin_edges = [0, 20, 40, 60, 80, 100]
# Create the histogram plot directly
plt.hist(a, bins=bin_edges, edgecolor='black') # Add edgecolor for clarity
plt.title("Data Distribution Histogram")
plt.xlabel("Value Ranges (Bins)")
plt.ylabel("Frequency (Count)")
plt.xticks(bin_edges) # Set x-axis ticks to match bin edges
plt.show()

Expected Output Description:

This code will display a window containing a bar chart (histogram). The x-axis represents the value ranges (0-20, 20-40, …, 80-100). The y-axis represents the frequency (count) of data points within each range. There will be 5 bars, with heights corresponding to the counts calculated previously (approximately 4, 3, 5, 2, 1). The bars have black edges for better visibility.