Overview
A column of numbers has a shape: where the values pile up, whether one side trails off further than the other, how heavy the tails are. Many methods quietly assume that shape is the bell curve of a normal distribution, so it pays to look before trusting them. You can summarise the shape with numbers (skewness for asymmetry, kurtosis for tail weight), test it against the normal with a p-value, or draw it. A histogram counts values in bins. A kernel density estimate replaces each value with a small smooth bump and adds the bumps into a curve. A Q-Q plot lines up the sorted data against the values a normal distribution would give, and a straight line means a match. Everything here returns numbers ready to plot.
A short history
The tools gathered here come from a century of work. Karl Pearson defined skewness in the 1890s. Kolmogorov and Smirnov developed tests based on the empirical distribution function in the 1930s, and Samuel Shapiro and Martin Wilk published their normality test in 1965. Wilk and Ram Gnanadesikan described quantile plots in 1968, and Murray Rosenblatt (1956) and Emanuel Parzen (1962) introduced kernel density estimation as a smooth alternative to the histogram.
How it works
- Compute skewness and excess kurtosis from the central moments of the sample.
- Run the Jarque-Bera test, which combines the two into one statistic and a p-value.
- Run the Anderson-Darling test, which compares the sample's cumulative distribution with a fitted normal and gives extra weight to the tails.
- Build Q-Q points with qq: sorted data against standard normal quantiles, plus the fitted line and its correlation.
- Estimate the density with histogram_pdf, choosing the number of bins by the Freedman-Diaconis, Sturges or square-root rule.
- Estimate the cumulative distribution with ecdf: at each value, the share of the data at or below it.
- Estimate a smooth density with kde, a Gaussian kernel with Silverman's or Scott's bandwidth, the width of each bump.
- Call summary for the moments, both tests and the Q-Q correlation in one result.
Watch out for
- With large samples the normality tests reject for deviations too small to matter, because their power grows with . Read the Q-Q correlation and the moments next to the p-value.
- With small samples the tests rarely reject, so a pass is weak evidence of normality. The Jarque-Bera approximation is rough below a few hundred observations.
- The kernel density estimate depends strongly on the bandwidth. Too small gives a spiky curve that follows noise, too large smooths real peaks away.
- Rule-of-thumb bandwidths are tuned for one-peaked, roughly normal data. On data with two peaks they tend to smooth too much and merge the peaks.
- A Gaussian kernel puts density beyond the edges of the data, so for values that cannot be negative the curve leaks below zero.
Use cases
When to use it
Before choosing a model, a transform or a test: to decide whether a log transform is needed, whether mean and standard deviation describe the column fairly, and whether a method that assumes normal errors is safe.
In industry
- Quality engineering
- Before computing process capability, engineers check with a Q-Q plot and a normality test that a part dimension is close to normal.
- Insurance
- Actuaries study the skewness and tail of claim sizes to choose a suitable distribution, since a few very large claims dominate cost.
- Machine learning
- Teams inspect feature histograms and skewness to decide whether a log or power transformation is needed before fitting a model.
Choosing it: what must hold
- A single numeric column with enough values, usually at least a few dozen, to show a shape.
- Observations that are roughly independent; a time ordered series needs time series methods first.
- A reason to care about shape, such as a later method that assumes normality or a choice of transformation.
When to choose something else
| If | Use instead |
|---|---|
| You only need centre and spread, not the shape | Mean, median and mode with standard deviation or quartiles and IQR |
| The sample is very large, so a normality test rejects for trivial departures | Judge by the Q-Q plot, skewness and kurtosis instead of the p-value |
| The question is about several columns jointly | Multivariate analysis |
Math foundations
Skewness
The third central moment, scaled to have no unit. Positive means a longer right tail, negative a longer left tail, zero a symmetric sample.
Jarque-Bera statistic
A normal sample has skewness and excess kurtosis near zero. Under normality follows a chi-square distribution with 2 degrees of freedom, so the p-value is .
Anderson-Darling statistic
A distance between the sample's cumulative distribution and the normal one, built from the sorted standardised values. The logarithms make gaps in the tails count more. The template then adjusts it for sample size.
Empirical CDF
The share of the data at or below . It is a staircase that rises by at each observation and needs no bins or bandwidth.
Kernel density estimate
Each observation contributes a normal bump of width centred on itself. The sum of the bumps, divided so the total area is 1, is the density curve.
Silverman's bandwidth
A rule of thumb for . It takes the smaller of two spread estimates so outliers do not widen the bumps, and shrinks slowly as the sample grows.
Freedman-Diaconis bin width
A histogram bin width based on the interquartile range, so outliers do not stretch it. The number of bins is the data range divided by , rounded up.
Symbols
- the i-th value of the sample
- number of values
- the k-th central moment
- sample skewness and excess kurtosis
- the i-th smallest value after subtracting the mean and dividing by the standard deviation
- standard normal cumulative distribution function
- standard normal density
- 1 when the condition holds, 0 otherwise
- the bandwidth: width of each kernel bump
- sample standard deviation
- interquartile range, third quartile minus first
- histogram bin width
Worked by hand
A sample of values has skewness , excess kurtosis , standard deviation and interquartile range 2.4. Test normality with Jarque-Bera and find Silverman's bandwidth.
The p-value of 0.0155 is below 0.05, so normality is rejected at the default level. Each kernel bump gets a width of about 0.64.
Visual example
Loading the example.
Try this
- Choose two bumps and raise the bandwidth multiple to 3: the density estimate smooths the two groups into one.
- Switch to the normal Q-Q plot and compare the long right tail with the normal shape.
- Set n to 30 on the heavy tails and draw new samples: see how often the tests fail to reject normality.
Code sample
import numpy as np
from impl import DistributionAnalysis
from config import DistributionAnalysisConfig
x = np.random.default_rng(0).lognormal(size=2000)
d = DistributionAnalysis(DistributionAnalysisConfig(bandwidth="silverman", bins="fd"))
print(d.skewness(x)) # clearly positive: long right tail
print(d.anderson_darling(x)["normal"]) # False
print(d.anderson_darling(np.log(x))["normal"]) # True: the log of the data is normal
grid, density = d.kde(x) # KDE curve, shapes (200,), (200,)
values, cdf = d.ecdf(x) # empirical CDF
q = d.qq(np.log(x)) # Q-Q points; q["r"] is close to 1Read the implementation (201 lines)
"""Distribution analysis of one numeric variable.
NumPy and the standard library only. Moments (skewness, excess kurtosis), two normality tests (Jarque-Bera and
Anderson-Darling), the points of a normal Q-Q plot, and three estimates of the distribution itself: a histogram
density (PDF), the empirical CDF, and a Gaussian kernel density estimate (KDE).
"""
from __future__ import annotations
import math
from statistics import NormalDist
import numpy as np
try:
from .config import DistributionAnalysisConfig
except ImportError: # run from the template's own folder
from config import DistributionAnalysisConfig
_NORMAL = NormalDist()
_normal_cdf = np.vectorize(_NORMAL.cdf, otypes=[float])
_normal_quantile = np.vectorize(_NORMAL.inv_cdf, otypes=[float])
_SQRT_2PI = math.sqrt(2.0 * math.pi)
class DistributionAnalysis:
"""Skewness, normality tests, Q-Q points and PDF/CDF/KDE estimates for a sample of shape (n,)."""
def __init__(self, config: DistributionAnalysisConfig | None = None) -> None:
self.config = config or DistributionAnalysisConfig()
@staticmethod
def _clean(values, minimum: int = 1) -> np.ndarray:
x = np.asarray(values, dtype=float).ravel()
x = x[~np.isnan(x)]
if x.size < minimum:
raise ValueError(f"at least {minimum} values are needed, got {x.size}")
return x
# ---- moments -------------------------------------------------------------------------------------------
def skewness(self, values, bias: bool = True) -> float:
"""Skewness g1 = m3 / m2^1.5. Positive: long right tail. Negative: long left tail. Zero: symmetric.
bias=False returns the sample-size adjusted G1 = g1 * sqrt(n (n - 1)) / (n - 2).
"""
x = self._clean(values, 3)
d = x - x.mean()
m2 = float(np.mean(d**2))
if m2 == 0:
raise ValueError("skewness is undefined for constant data")
g1 = float(np.mean(d**3)) / m2**1.5
n = x.size
return g1 if bias else g1 * math.sqrt(n * (n - 1.0)) / (n - 2.0)
def excess_kurtosis(self, values) -> float:
"""Excess kurtosis m4 / m2^2 - 3 (0 for a normal distribution; positive means heavy tails)."""
x = self._clean(values, 4)
d = x - x.mean()
m2 = float(np.mean(d**2))
if m2 == 0:
raise ValueError("kurtosis is undefined for constant data")
return float(np.mean(d**4)) / m2**2 - 3.0
# ---- normality tests -----------------------------------------------------------------------------------
def jarque_bera(self, values) -> dict:
"""Jarque-Bera test: JB = n/6 * (S^2 + K^2 / 4) with skewness S and excess kurtosis K.
Under normality JB follows a chi-square distribution with 2 degrees of freedom, so p = exp(-JB / 2).
The approximation is rough below a few hundred observations. Returns {"statistic", "p_value", "normal"};
"normal" is True when normality is not rejected at config.alpha.
"""
x = self._clean(values, 4)
statistic = x.size / 6.0 * (self.skewness(x) ** 2 + self.excess_kurtosis(x) ** 2 / 4.0)
p_value = math.exp(-statistic / 2.0)
return {"statistic": statistic, "p_value": p_value, "normal": p_value > self.config.alpha}
def anderson_darling(self, values) -> dict:
"""Anderson-Darling test of normality with mean and variance estimated from the sample.
The statistic is adjusted for sample size, A* = A^2 * (1 + 0.75 / n + 2.25 / n^2), and the p-value comes
from the formulas of D'Agostino and Stephens (1986). It weights the tails more than other
distribution-function tests and works well from about n = 8 up.
Returns {"statistic" (A*), "p_value", "normal"}.
"""
x = np.sort(self._clean(values, 8))
n = x.size
std = x.std(ddof=1)
if std == 0:
raise ValueError("the test is undefined for constant data")
cdf = np.clip(_normal_cdf((x - x.mean()) / std), 1e-300, 1.0 - 1e-16)
i = np.arange(1, n + 1)
a2 = -n - float(np.sum((2 * i - 1) * (np.log(cdf) + np.log1p(-cdf[::-1])))) / n
a = a2 * (1.0 + 0.75 / n + 2.25 / n**2)
if a >= 0.6:
p_value = math.exp(1.2937 - 5.709 * a + 0.0186 * a * a)
elif a >= 0.34:
p_value = math.exp(0.9177 - 4.279 * a - 1.38 * a * a)
elif a >= 0.2:
p_value = 1.0 - math.exp(-8.318 + 42.796 * a - 59.938 * a * a)
else:
p_value = 1.0 - math.exp(-13.436 + 101.14 * a - 223.73 * a * a)
p_value = min(max(p_value, 0.0), 1.0)
return {"statistic": a, "p_value": p_value, "normal": p_value > self.config.alpha}
# ---- Q-Q plot ------------------------------------------------------------------------------------------
def qq(self, values) -> dict:
"""Points of a normal Q-Q plot and the straight line through them.
Returns {"theoretical" (n,), "sample" (n,), "slope", "intercept", "r"}: standard normal quantiles at the
plotting positions (i - 0.375) / (n + 0.25), the sorted data, and the least-squares line
sample = intercept + slope * theoretical. For normal data the points lie on a line with slope close to
the standard deviation, intercept close to the mean, and r close to 1.
"""
x = np.sort(self._clean(values, 3))
n = x.size
theoretical = _normal_quantile((np.arange(1, n + 1) - 0.375) / (n + 0.25))
slope, intercept = np.polyfit(theoretical, x, 1)
r = float(np.corrcoef(theoretical, x)[0, 1]) if x.std() > 0 else float("nan")
return {"theoretical": theoretical, "sample": x, "slope": float(slope), "intercept": float(intercept), "r": r}
# ---- PDF, CDF, KDE -------------------------------------------------------------------------------------
def n_bins(self, values) -> int:
"""Number of histogram bins chosen by config.bins for this sample."""
x = self._clean(values)
rule = self.config.bins
if not isinstance(rule, str):
return int(rule)
n = x.size
if rule == "sturges":
return int(math.ceil(math.log2(n))) + 1
if rule == "sqrt":
return int(math.ceil(math.sqrt(n)))
q1, q3 = np.quantile(x, [0.25, 0.75])
width = 2.0 * (q3 - q1) / n ** (1.0 / 3.0) # Freedman-Diaconis
span = float(x.max() - x.min())
if width <= 0 or span == 0:
return int(math.ceil(math.log2(n))) + 1
return max(1, int(math.ceil(span / width)))
def histogram_pdf(self, values) -> tuple[np.ndarray, np.ndarray]:
"""Histogram estimate of the density. Returns (density (b,), edges (b + 1,)); sum(density * widths) = 1."""
x = self._clean(values)
counts, edges = np.histogram(x, bins=self.n_bins(x))
return counts / (x.size * np.diff(edges)), edges
def ecdf(self, values) -> tuple[np.ndarray, np.ndarray]:
"""Empirical CDF. Returns (sorted distinct values (m,), F (m,)) with F[k] = share of data <= value k."""
x = self._clean(values)
distinct, counts = np.unique(x, return_counts=True)
return distinct, np.cumsum(counts) / x.size
def bandwidth(self, values) -> float:
"""KDE bandwidth h for this sample.
silverman: 0.9 * min(sd, IQR / 1.34) * n^(-1/5). scott: 1.06 * sd * n^(-1/5). A number: used as is.
"""
if not isinstance(self.config.bandwidth, str):
return float(self.config.bandwidth)
x = self._clean(values, 2)
sd = float(x.std(ddof=1))
if self.config.bandwidth == "scott":
spread = sd
factor = 1.06
else:
q1, q3 = np.quantile(x, [0.25, 0.75])
iqr = float(q3 - q1) / 1.34
spread = min(sd, iqr) if iqr > 0 else sd
factor = 0.9
if spread <= 0:
raise ValueError("a rule-of-thumb bandwidth needs data that vary; pass a numeric bandwidth instead")
return factor * spread * x.size ** (-0.2)
def kde(self, values, grid=None) -> tuple[np.ndarray, np.ndarray]:
"""Gaussian kernel density estimate f(t) = 1 / (n h) * sum(phi((t - x_i) / h)).
values: shape (n,). grid: points to evaluate at, shape (g,); by default config.grid_size points spanning
the data plus three bandwidths on each side. Returns (grid (g,), density (g,)).
"""
x = self._clean(values)
h = self.bandwidth(x)
if grid is None:
grid = np.linspace(x.min() - 3.0 * h, x.max() + 3.0 * h, self.config.grid_size)
grid = np.asarray(grid, dtype=float).ravel()
density = np.empty(grid.size)
for start in range(0, grid.size, 256): # chunks keep the (g, n) work array small
z = (grid[start:start + 256, None] - x[None, :]) / h
density[start:start + 256] = np.exp(-0.5 * z * z).sum(axis=1) / (x.size * h * _SQRT_2PI)
return grid, density
def summary(self, values) -> dict:
"""One-call overview: n, mean, std, skewness, excess kurtosis, both normality tests and the Q-Q r."""
x = self._clean(values, 8)
return {
"n": int(x.size),
"mean": float(x.mean()),
"std": float(x.std(ddof=1)),
"skewness": self.skewness(x),
"excess_kurtosis": self.excess_kurtosis(x),
"jarque_bera": self.jarque_bera(x),
"anderson_darling": self.anderson_darling(x),
"qq_r": self.qq(x)["r"],
}- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 10, run with
python3 -m unittest -v
Practice
Draw 2000 lognormal values with NumPy and create a DistributionAnalysis. Compare skewness, jarque_bera and anderson_darling on the values and on their logarithm. Then compute kde three times with bandwidth set to 0.05, to silverman and to 2.0 in DistributionAnalysisConfig, and describe how the curve changes.
Check on learning
- A sample of one million values fails both normality tests, yet its Q-Q correlation is 0.9995. Would you treat the column as normal for a method that assumes it?
A way to think about it
Separate statistical significance from practical size. Ask how large a deviation the method can tolerate, and what the tests detect at this .
- Why does Silverman's rule use the smaller of the standard deviation and the scaled IQR instead of the standard deviation alone?
A way to think about it
Add a few extreme outliers to a sample. See which spread estimate moves, and what a too-large does to the curve.
- Your data have two clear peaks. What does a kernel density estimate with a very large bandwidth show, and what would the Q-Q plot look like?
A way to think about it
Wide bumps overlap into one hill. On the Q-Q plot, think about where the data have a gap that a normal distribution would fill.
- The Anderson-Darling and Jarque-Bera tests disagree on a sample. What kinds of departure from normality does each one see best?
A way to think about it
Jarque-Bera only looks at two moments. Anderson-Darling compares the whole distribution function, with emphasis on the tails.
- Why does the empirical CDF need no tuning choice while the histogram and the kernel estimate both do?
A way to think about it
A density is a rate of change of the CDF. Estimating a rate from scattered points requires deciding how far to look on each side.