hist() (Matplotlib)

ax.hist() draws a histogram, grouping continuous data into bins and drawing a bar for each bin whose height is the count of values that fell into it. It reveals the distribution of a single variable.

Matplotlib

A histogram answers 'how is this data distributed?' — where the values cluster, whether they are skewed, and where the outliers lie. The bins argument controls the grouping: a single integer sets the number of equal-width bins, while a list specifies exact bin edges.

Choosing the bin count matters: too few hides structure, too many adds noise. Set density=True to normalize the bars so they integrate to 1 (turning counts into a probability density), useful for comparing distributions of different sizes.

hist returns three things — the counts per bin, the bin edges, and the bar patches — so you can capture the numbers as well as the picture. Don't confuse it with bar(), which charts pre-categorized values rather than binning continuous data.

Syntax

ax.hist(data, bins=10, density=False)

Examples

Python — Counts of values in each of the 3 bins.

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
counts, edges, patches = ax.hist(np.array([1, 1, 2, 3, 3, 3]), bins=3)
print(counts)

Output:

[2. 1. 3.]

Learn it in a lesson

See also

Back to the Dictionary