TExcelTAD
Home › Statistics › Histograms

Histograms

A histogram is a picture of a grouped frequency table for quantitative data. The horizontal axis is divided into intervals (bins), and each bar's height shows how many observations fall into that bin. Unlike a bar chart, the bars touch, because the bins cover a continuous number line with no gaps.

Histograms answer the "shape" questions at a glance: Where is the peak? Is the data symmetric or skewed? Are there gaps, several peaks or outliers?

A first histogram

Here are the commute times (minutes) of the 40 employees from Frequency Tables, drawn with Matplotlib:

python · try it yourself
import matplotlib.pyplot as plt

commute = [22, 35, 18, 41, 27, 30, 25, 52, 33, 29, 19, 24, 38, 31, 27, 45, 23, 28, 36, 26,
           21, 34, 30, 58, 27, 32, 25, 29, 40, 24, 17, 31, 28, 37, 26, 33, 22, 30, 47, 28]

fig, ax = plt.subplots(figsize=(6, 3.5))
counts, edges, _ = ax.hist(commute, bins=range(10, 70, 10), color="#2a78d6", edgecolor="white")
ax.set_xlabel("commute time (minutes)")
ax.set_ylabel("employees")
ax.set_title("Commute times of 40 employees")
plt.tight_layout()
plt.show()

for left, c in zip(edges[:-1], counts):
    print(f"[{left:.0f}, {left + 10:.0f}): {c:.0f}")
[10, 20): 3
[20, 30): 18
[30, 40): 13
[40, 50): 4
[50, 60): 2

ax.hist returns the counts and bin edges, so you can print the frequency table behind the picture. Most employees need 20–40 minutes, and the long tail to the right (up to 58 minutes) shows the data is right-skewed.

Note: NumPy and Matplotlib put a value equal to an inner bin edge into the bin on its right: 30 belongs to [30, 40). Only the very last bin includes its right edge.

Bin width changes the story

The same data can look quite different with different bin widths. Too wide and you lose the shape; too narrow and the picture becomes noisy. Here are 500 simulated reaction times drawn three ways:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(12)
reaction_ms = rng.normal(250, 35, size=500)

fig, axes = plt.subplots(1, 3, figsize=(10, 3), sharey=False)
for ax, bins in zip(axes, [4, 15, 80]):
    ax.hist(reaction_ms, bins=bins, color="#2a78d6", edgecolor="white", linewidth=0.5)
    ax.set_title(f"{bins} bins")
    ax.set_xlabel("reaction time (ms)")
fig.tight_layout()
plt.show()
print("Drew the same 500 reaction times with 4, 15 and 80 bins")
Drew the same 500 reaction times with 4, 15 and 80 bins

Fifteen bins show the familiar bell shape clearly; four hide it; eighty make it ragged. NumPy can suggest a bin count with rules such as Sturges or Freedman–Diaconis (bins="auto" picks the better of the two):

python · try it yourself
import numpy as np

rng = np.random.default_rng(12)
reaction_ms = rng.normal(250, 35, size=500)

for rule in ["sturges", "fd", "auto"]:
    edges = np.histogram_bin_edges(reaction_ms, bins=rule)
    print(f"{rule:8s}: {len(edges) - 1} bins of width {edges[1] - edges[0]:.1f} ms")
sturges : 10 bins of width 19.9 ms
fd      : 18 bins of width 11.1 ms
auto    : 18 bins of width 11.1 ms

Reading shapes

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(4)
shapes = {
    "symmetric": rng.normal(50, 10, 1000),
    "right-skewed": rng.gamma(2, 8, 1000),
    "bimodal": np.concatenate([rng.normal(35, 5, 500), rng.normal(65, 5, 500)]),
}

fig, axes = plt.subplots(1, 3, figsize=(10, 3))
for ax, (name, data) in zip(axes, shapes.items()):
    ax.hist(data, bins=25, color="#2a78d6", edgecolor="white", linewidth=0.5)
    ax.set_title(name)
fig.tight_layout()
plt.show()
for name, data in shapes.items():
    print(f"{name:12s} mean={data.mean():5.1f}  median={np.median(data):5.1f}")
symmetric    mean= 49.9  median= 49.8
right-skewed mean= 15.7  median= 13.4
bimodal      mean= 50.0  median= 47.1
  • Symmetric: mean and median nearly equal.
  • Right-skewed: the mean is pulled towards the long right tail.
  • Bimodal: two peaks often mean two different groups are mixed together (for example weekday and weekend customers). The mean, sitting in the valley between peaks, describes almost nobody.

Histograms of densities

With density=True the bar areas sum to 1, so the vertical axis shows a probability density instead of counts. That makes it possible to compare datasets of different sizes, or to lay a theoretical curve on top, as you will do in Normal Distribution.

python · try it yourself
import numpy as np

rng = np.random.default_rng(12)
data = rng.normal(250, 35, size=500)
density, edges = np.histogram(data, bins=15, density=True)
widths = np.diff(edges)
print("sum of heights * widths =", round(float((density * widths).sum()), 6))
sum of heights * widths = 1.0

Test yourself

Why do the bars of a histogram touch each other?

  1. To save space
  2. Because the bins cover a continuous range of numbers without gaps
  3. Because the data is categorical
  4. It is just a style choice with no meaning

A histogram has two clear peaks. What is a likely explanation?

  1. The data is normally distributed
  2. Two different groups are mixed in the data
  3. The bins are too wide
  4. There are missing values

What does density=True change in plt.hist?

  1. Nothing visible
  2. Bar areas sum to 1, so heights are densities instead of counts
  3. It removes outliers
  4. It sorts the data