Histograms and Distributions
A histogram bins numeric data to show how values are distributed.
Syntax
plt.hist(data, bins=20)A histogram splits a numeric column into bins and counts how many values fall in each. It reveals the distribution: is it centred, skewed, bimodal?
Why it matters for ML
Many models assume roughly normal, similarly-scaled features. A histogram shows skew and outliers before you train.
Example
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(0)
heights = rng.normal(170, 8, 500) # mean 170, sd 8
plt.hist(heights, bins=20)
plt.title('Distribution of heights')
plt.xlabel('height (cm)')
plt.ylabel('count')
plt.show()When to use it
- A data scientist plots histograms of each numeric feature before modelling to detect skewed distributions that may need log transformation.
- An ML engineer overlays histograms of a feature for each class label to see whether the feature has discriminative power for classification.
- A quality analyst checks the histogram of model prediction probabilities to confirm they are well-spread rather than collapsed near 0.5.
More examples
Basic histogram of a feature
Draws a 20-bin histogram of a synthetic age distribution, revealing the bell-curve shape of normally distributed data.
import matplotlib.pyplot as plt
import numpy as np
ages = np.random.normal(loc=35, scale=10, size=500)
plt.hist(ages, bins=20, edgecolor='black')
plt.xlabel('Age'); plt.ylabel('Count')
plt.title('Age Distribution')
plt.show()Overlaid histograms by class
Overlays two semi-transparent histograms for two classes to show where their feature distributions overlap, indicating difficulty of classification.
import matplotlib.pyplot as plt
import numpy as np
neg = np.random.normal(0, 1, 300)
pos = np.random.normal(2, 1, 300)
plt.hist(neg, bins=30, alpha=0.6, label='class 0')
plt.hist(pos, bins=30, alpha=0.6, label='class 1')
plt.legend()
plt.title('Feature Distribution by Class')
plt.show()Density plot with KDE
Overlays a smooth KDE curve on top of a density-normalised histogram to reveal a bimodal distribution that a raw histogram might obscure.
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
data = np.concatenate([np.random.normal(0, 1, 200), np.random.normal(4, 1, 200)])
plt.hist(data, bins=30, density=True, alpha=0.5, label='histogram')
kde = gaussian_kde(data)
x = np.linspace(data.min(), data.max(), 200)
plt.plot(x, kde(x), lw=2, label='KDE')
plt.legend(); plt.title('Bimodal Distribution')
plt.show()
Discussion