svgmahalanobis-qq
χ² Q–Q plot of Mahalanobis distances
Are the rows (or residuals) multivariate normal, and which rows are multivariate outliers?
How to read it
- Read points as rows' squared distance from the centre, sorted.
- Under multivariate normality they follow the dashed line.
- Points above the horizontal cutoff are candidate outliers.
- Callout 1: Rows above the cutoff: candidate multivariate outliers.
- Callout 2: On the line: consistent with normality.
- 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
# χ² 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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 = go.Figure()
fig.add_scatter(x=np.r_[theo, theo[::-1]], y=np.r_[lo, hi[::-1]], fill="toself", fillcolor="rgba(120,120,120,0.15)", line=dict(width=0), name="95% pointwise envelope")
fig.add_scatter(x=theo, y=theo, mode="lines", line=dict(color=REF, dash="dash", width=1), showlegend=False)
fig.add_hline(y=cut, line_dash="dot", line_color=REF)
fig.add_scatter(x=theo[obs <= cut], y=obs[obs <= cut], mode="markers", marker=dict(color=PALETTE[0], size=5), name="rows")
fig.add_scatter(x=theo[obs > cut], y=obs[obs > cut], mode="markers", marker=dict(color=PALETTE[1], size=6), name=f"beyond χ² 97.5% ({(obs > cut).sum()})")
fig.update_layout(xaxis_title="χ² quantile", yaxis_title="Squared Mahalanobis distance")
fig.show()Needs pandas, numpy, plotly, scipy · reads mahalanobis-qq-demo.csv · app theme from the optional codesplash helper
# χ² Q–Q plot of Mahalanobis distances — Codesplash Chart Lab (recipe "mahalanobis-qq")
# controls: df=2, envelope=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("mahalanobis-qq-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
D <- "D² of each row"
K <- 2 # degrees of freedom: the number of variables
obs <- sort(df[[D]])
n <- length(obs); r <- seq_len(n)
d <- data.frame(theo = qchisq((r - 0.5) / n, K), obs = obs, lo = qchisq(qbeta(0.025, r, n - r + 1), K), hi = qchisq(qbeta(0.975, r, n - r + 1), K))
cut <- qchisq(0.975, K)
d$out <- d$obs > cut
p <- ggplot(d, aes(theo, obs)) +
geom_ribbon(aes(ymin = lo, ymax = hi), fill = cs_cat[1], alpha = 0.12) +
geom_abline(slope = 1, intercept = 0, colour = ref_col, linetype = "dashed") +
geom_hline(yintercept = cut, colour = ref_col, linetype = "dotted") +
geom_point(aes(colour = out), size = 1.3) +
scale_colour_manual(values = cs_cat[1:2], labels = c("rows", "beyond χ² 97.5%"), name = NULL) +
labs(x = "χ² quantile", y = "Squared Mahalanobis distance") + theme_cs
print(p)Needs ggplot2 · reads mahalanobis-qq-demo.csv · app theme from the optional codesplashr helper