Skip to content
svgmahalanobis-qq

χ² Q–Q plot of Mahalanobis distances

Are the rows (or residuals) multivariate normal, and which rows are multivariate outliers?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read points as rows' squared distance from the centre, sorted.
  2. Under multivariate normality they follow the dashed line.
  3. Points above the horizontal cutoff are candidate outliers.
  1. Callout 1: Rows above the cutoff: candidate multivariate outliers.
  2. Callout 2: On the line: consistent with normality.
  3. Callout 3: The χ² 97.5% cutoff.

Watch out

  • Outliers pull the mean and covariance towards themselves, which can mask other outliers.

Defaults

Degrees of freedom (number of variables)
2
The χ² reference: the number of variables behind the distances.
Range 1 to 50, step 1
Show the 95% envelope
On
Shade the range a multivariate normal sample would stay inside.

Pinned in the code

  • Plotting positions (i − ½)/n against the χ² distribution with df = number of variables; under multivariate normality the points follow the dashed identity line.
  • The shaded band is a pointwise 95% envelope: the 2.5% and 97.5% quantiles of the i-th uniform order statistic, Beta(i, n − i + 1), mapped through the χ² quantile function.
  • Distances come from the engine (rows centred on their group mean, the pooled covariance); with estimated means and covariance the exact reference is a scaled beta, so the χ² line is an approximation for small n.
  • Upward curvature in the right tail signals heavy tails (high multivariate kurtosis); isolated points above the χ² 97.5% line are candidate outliers, not proof.
# χ² Q–Q plot of Mahalanobis distances — Codesplash Chart Lab (recipe "mahalanobis-qq")
# controls: df=2, envelope=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]

df = pd.read_csv("mahalanobis-qq-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
D = "D² of each row"
K = 2  # degrees of freedom: the number of variables
obs = np.sort(df[D].dropna().to_numpy(float))
n = len(obs)
r = np.arange(1, n + 1)
theo = stats.chi2.ppf((r - 0.5) / n, K)  # plotting positions (i − ½)/n
lo = stats.chi2.ppf(stats.beta.ppf(0.025, r, n - r + 1), K)  # order-statistic quantiles
hi = stats.chi2.ppf(stats.beta.ppf(0.975, r, n - r + 1), K)
cut = stats.chi2.ppf(0.975, K)
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.fill_between(theo, lo, hi, color=PALETTE[0], alpha=0.12, label="95% pointwise envelope")
ax.plot(theo, theo, color=REF, linestyle="--", linewidth=1)
ax.axhline(cut, color=REF, linestyle=":", linewidth=1)
ax.scatter(theo[obs <= cut], obs[obs <= cut], s=14, color=PALETTE[0], label="rows")
ax.scatter(theo[obs > cut], obs[obs > cut], s=16, color=PALETTE[1], label=f"beyond χ² 97.5% ({(obs > cut).sum()})")
ax.set_xlabel("χ² quantile")
ax.set_ylabel("Squared Mahalanobis distance")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads mahalanobis-qq-demo.csv · app theme from the optional codesplash helper