A histogram shows the distribution of a numeric variable: how many values fall into each range (bin). It answers questions like “Are most students scoring between 60 and 80?” and helps spot skew and outliers before modelling.
Prerequisites
Basic Histogram
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(0)
marks = rng.normal(65, 12, 500).clip(0, 100)
fig, ax = plt.subplots()
ax.hist(marks, bins=20, color='skyblue', edgecolor='black')
ax.set_xlabel('Marks')
ax.set_ylabel('Number of students')
plt.show()
Explanation: The range of marks is split into 20 equal bins and each bar’s height is the count in that bin. The shape here is a bell curve because the data comes from a normal distribution.
Choosing Bins
fig, axes = plt.subplots(1, 3, figsize=(12, 3))
for ax, b in zip(axes, [5, 20, 60]):
ax.hist(marks, bins=b)
ax.set_title(f'bins={b}')
plt.show()
Explanation: Too few bins hide detail; too many make the chart noisy. You can also pass edges like bins=[0, 40, 60, 80, 100] or bins='auto'.
Compare Two Groups
a = rng.normal(60, 10, 300)
b = rng.normal(72, 8, 300)
fig, ax = plt.subplots()
ax.hist(a, bins=25, alpha=0.5, label='Batch A')
ax.hist(b, bins=25, alpha=0.5, label='Batch B')
ax.legend()
plt.show()
Density and Cumulative
fig, ax = plt.subplots()
ax.hist(marks, bins=20, density=True)
ax.hist(marks, bins=20, density=True, cumulative=True, histtype='step')
plt.show()
Explanation: density=True scales bars so the area is 1 (a probability density). cumulative shows the running total.
Get the Counts
counts, edges, _ = ax.hist(marks, bins=5)
print(counts, edges.round(1))
Practice Exercises
- Plot the distribution of 1000 dice-roll sums (two dice).
- Compare histograms of male and female heights.
Interview Questions
Q: Bar chart vs histogram?
Bar charts compare categories; histograms show the distribution of continuous data in bins.
Summary
Use ax.hist with sensible bins, alpha for overlapping groups, and density/cumulative for probability views.
Next: Subplots
Machine Learning Tutorials, Courses and Certifications