np.histogram() divides the range of the data into a number of equal-width bins, 10 by default, or a specific number/explicit bin edges you provide, counts how many values fall into each bin, and returns two arrays: the counts per bin, and the bin edges, one more element than the counts, since each bin has a start and end edge. Despite the name, it purely computes numbers — actually visualizing the result as a bar chart requires a separate plotting call, such as with Matplotlib's own hist() function or by feeding this function's output into a bar plot.
1Understanding np.histogram()
np.histogram() divides the range of the data into a number of equal-width bins, 10 by default, or a specific number/explicit bin edges you provide, counts how many values fall into each bin, and returns two arrays: the counts per bin, and the bin edges, one more element than the counts, since each bin has a start and end edge. Despite the name, it purely computes numbers — actually visualizing the result as a bar chart requires a separate plotting call, such as with Matplotlib's own hist() function or by feeding this function's output into a bar plot.
np.histogram() only computes the numeric bin counts and edges — it doesn't draw anything. For a quick visual histogram in a script, matplotlib's plt.hist() is usually more convenient, since it computes and plots in one call; use np.histogram() directly when you need the raw numbers for further processing.
import numpy as np
data = np.array([1, 2, 2, 3, 3, 3, 4, 4, 5])
counts, edges = np.histogram(data, bins=5)
print(counts)
print(edges)2Practical Example
Here is a real-world application of np.histogram() showing how it is used in production NumPy code.
import numpy as np
data = np.random.default_rng(0).normal(0, 1, 1000)
counts, edges = np.histogram(data, bins=[-3, -1, 1, 3])
print(counts)3Best Practices
Follow these guidelines when working with np.histogram():
1. Use np.histogram() when you need the raw bin counts and edges for further numeric processing, not just a visualization
2. Choose an appropriate number of bins deliberately for your dataset's size and range, rather than always relying on the default of 10
3. Pass explicit bin edges as an array when you need consistent, comparable bins across multiple different histograms
Tip: np.histogram() only computes the numeric bin counts and edges — it doesn't draw anything. For a quick visual histogram in a script, matplotlib's plt.hist() is usually more convenient, since it computes and plots in one call; use np.histogram() directly when you need the raw numbers for further processing.
import numpy as np
data = np.array([1, 2, 2, 3, 3, 3, 4, 4, 5])
counts, edges = np.histogram(data, bins=5)
print(counts)
print(edges)