Histograms

bins, density, and overlaying a second sample.

A histogram counts how many samples fall in each bin. It is for a distribution, not for labelled categories.

Goal

Choose bins, overlay two samples, and try density=True.

Default bins

rng = np.random.default_rng(0)
temps = 26 + rng.normal(scale=1.2, size=200)
fig, ax = plt.subplots()
ax.hist(temps, color="#1d4f7a", edgecolor="white")
ax.set_xlabel("°C")
ax.set_ylabel("count")
ax.set_title("Nairobi-like daily max")
plt.show()

More bins

rng = np.random.default_rng(0)
temps = 26 + rng.normal(scale=1.2, size=200)
fig, ax = plt.subplots()
ax.hist(temps, bins=20, edgecolor="white")
ax.set_title("bins=20")
plt.show()

Too many bins look noisy; too few hide the shape.

Overlay

rng = np.random.default_rng(0)
nairobi = 26 + rng.normal(scale=1.2, size=200)
mombasa = 31 + rng.normal(scale=0.8, size=200)
fig, ax = plt.subplots()
ax.hist(nairobi, bins=18, alpha=0.6, label="Nairobi")
ax.hist(mombasa, bins=18, alpha=0.6, label="Mombasa")
ax.legend()
ax.set_xlabel("°C")
ax.set_title("Two cities")
plt.show()

alpha lets the overlap show. density=True would plot a density instead of raw counts — useful when the samples have different sizes.

Tip

Do not histogram already aggregated city totals (five numbers). Use bar for those.