svgbrushableqq
Normal Q–Q plot
Is a variable (or a set of residuals) approximately normal, and where does it depart?
How to read it
- Points on the straight line: the data match a normal shape.
- Look at the ends. Points above the line on the right and below on the left mean heavy tails; curving one way means skew.
- Compare with the envelope: points outside it stray further than chance alone would usually allow.
- Callout 1: Points on the line: this part of the data matches a normal shape.
- Callout 2: Above the line at the right: larger values than a normal would give.
- Callout 3: Below the line at the left: the lower tail is heavier too.
Watch out
- With thousands of rows, tiny departures fall outside the envelope without mattering for most methods.
- In small samples, even normal data can wander. Judge the pattern, not one point.
Defaults
- Pointwise envelope
- On
- Shade the range a correct normal sample would stay inside at each point.
- Envelope level
- 95%
- How often a correct normal sample would stay inside the envelope at each point.
- Also: 99%
- Detrended (worm plot)
- Off
- Subtract the line, so small departures are easier to see.
Pinned in the code
- Plotting positions: R `ppoints(n)` = (i − a)/(n + 1 − 2a), a = 3/8 for n ≤ 10 else 1/2; theoretical quantiles Φ⁻¹(pᵢ).
- Reference line: R `qqline` through the type-7 first and third quartiles of the sample and of N(0, 1) (robust to tails).
- Envelope: exact pointwise band from uniform order statistics, U₍ᵢ₎ ~ Beta(i, n−i+1) → Φ⁻¹(qbeta(α/2…1−α/2)) mapped through the qqline (not a simulation; not simultaneous). Points outside are flagged.
- Detrended: sample − qqline(z), the envelope shifted the same way.
# Normal Q–Q plot — Codesplash Chart Lab (recipe "qq")
# controls: envelope=true, level=0.95, detrended=false
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("qq-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
def ppoints(n):
"""R ppoints(n): (i − a)/(n + 1 − 2a) with a = 3/8 for n ≤ 10, else 1/2."""
a = 3 / 8 if n <= 10 else 0.5
return (np.arange(1, n + 1) - a) / (n + 1 - 2 * a)
x = np.sort(df["residual"].dropna().to_numpy(dtype=float))
n = x.size
z = stats.norm.ppf(ppoints(n)) # theoretical normal quantiles at R's plotting positions
q1, q3 = np.quantile(x, [0.25, 0.75]) # type 7, like R qqline
slope = (q3 - q1) / (stats.norm.ppf(0.75) - stats.norm.ppf(0.25))
intercept = q1 - slope * stats.norm.ppf(0.25)
line = intercept + slope * z
# exact pointwise envelope: U(i) ~ Beta(i, n − i + 1), through Φ⁻¹ and the qqline (not simultaneous)
i = np.arange(1, n + 1)
alpha = 1 - 0.95
lo = intercept + slope * stats.norm.ppf(stats.beta.ppf(alpha / 2, i, n - i + 1))
hi = intercept + slope * stats.norm.ppf(stats.beta.ppf(1 - alpha / 2, i, n - i + 1))
outside = (x < lo) | (x > hi)
y, ref = x, line
fig, ax = plt.subplots(figsize=(6, 5))
ax.fill_between(z, lo, hi, color=PALETTE[0], alpha=0.15, linewidth=0, label=f"{1 - alpha:.0%} pointwise envelope")
ax.plot(z, ref, color=plt.rcParams["text.color"], linewidth=1, label="qqline (quartiles)")
ax.scatter(z[~outside], y[~outside], s=14, color=PALETTE[0], linewidths=0)
ax.scatter(z[outside], y[outside], s=18, color=PALETTE[3], linewidths=0, label=f"{outside.sum()} outside the envelope")
ax.set_xlabel("Theoretical quantiles (normal)")
ax.set_ylabel("residual")
ax.legend()
plt.show()Needs pandas, numpy, matplotlib, scipy · reads qq-demo.csv · app theme from the optional codesplash helper
# Normal Q–Q plot — Codesplash Chart Lab (recipe "qq")
# controls: envelope=true, level=0.95, detrended=false
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("qq-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
def ppoints(n):
"""R ppoints(n): (i − a)/(n + 1 − 2a) with a = 3/8 for n ≤ 10, else 1/2."""
a = 3 / 8 if n <= 10 else 0.5
return (np.arange(1, n + 1) - a) / (n + 1 - 2 * a)
x = np.sort(df["residual"].dropna().to_numpy(dtype=float))
n = x.size
z = stats.norm.ppf(ppoints(n)) # theoretical normal quantiles at R's plotting positions
q1, q3 = np.quantile(x, [0.25, 0.75]) # type 7, like R qqline
slope = (q3 - q1) / (stats.norm.ppf(0.75) - stats.norm.ppf(0.25))
intercept = q1 - slope * stats.norm.ppf(0.25)
line = intercept + slope * z
# exact pointwise envelope: U(i) ~ Beta(i, n − i + 1), through Φ⁻¹ and the qqline (not simultaneous)
i = np.arange(1, n + 1)
alpha = 1 - 0.95
lo = intercept + slope * stats.norm.ppf(stats.beta.ppf(alpha / 2, i, n - i + 1))
hi = intercept + slope * stats.norm.ppf(stats.beta.ppf(1 - alpha / 2, i, n - i + 1))
outside = (x < lo) | (x > hi)
y, ref = x, line
INK = cs.palette(dark=False)["foreground"] if cs else "#131922"
fig = go.Figure()
fig.add_scatter(x=z, y=lo, mode="lines", line=dict(width=0), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=z, y=hi, mode="lines", line=dict(width=0), fill="tonexty", fillcolor="rgba(120, 140, 170, 0.18)", name=f"{1 - alpha:.0%} pointwise envelope")
fig.add_scatter(x=z, y=ref, mode="lines", line=dict(color=INK, width=1), name="qqline (quartiles)")
fig.add_scatter(x=z[~outside], y=y[~outside], mode="markers", marker=dict(color=PALETTE[0], size=6), name="inside")
fig.add_scatter(x=z[outside], y=y[outside], mode="markers", marker=dict(color=PALETTE[3], size=7), name=f"{outside.sum()} outside")
fig.update_layout(xaxis_title="Theoretical quantiles (normal)", yaxis_title="residual")
fig.show()Needs pandas, numpy, plotly, scipy · reads qq-demo.csv · app theme from the optional codesplash helper
# Normal Q–Q plot — Codesplash Chart Lab (recipe "qq")
# controls: envelope=true, level=0.95, detrended=false
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("qq-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
x <- sort(df[["residual"]][is.finite(df[["residual"]])])
n <- length(x)
z <- qnorm(ppoints(n)) # R plotting positions
q <- quantile(x, c(0.25, 0.75), type = 7) # qqline through the quartiles
slope <- diff(q) / diff(qnorm(c(0.25, 0.75)))
intercept <- q[[1]] - slope * qnorm(0.25)
line <- intercept + slope * z
qq <- data.frame(z = z, y = x, ref = line)
# exact pointwise envelope: U(i) ~ Beta(i, n − i + 1), through Φ⁻¹ and the qqline (not simultaneous)
i <- seq_len(n)
alpha <- 1 - 0.95
qq$lo <- intercept + slope * qnorm(qbeta(alpha / 2, i, n - i + 1))
qq$hi <- intercept + slope * qnorm(qbeta(1 - alpha / 2, i, n - i + 1))
qq$outside <- qq$y < qq$lo | qq$y > qq$hi
p <- ggplot(qq, aes(z))
p <- p + geom_ribbon(aes(ymin = lo, ymax = hi), fill = cs_cat[1], alpha = 0.15)
p <- p + geom_line(aes(y = ref), linewidth = 0.4) +
geom_point(aes(y = y, colour = outside), size = 1.4, show.legend = FALSE) +
scale_colour_manual(values = c(`FALSE` = cs_cat[1], `TRUE` = cs_cat[4])) +
labs(x = "Theoretical quantiles (normal)", y = "residual",
subtitle = sprintf("%d point(s) outside the pointwise envelope", sum(qq$outside))) +
theme_cs
print(p)Needs ggplot2 · reads qq-demo.csv · app theme from the optional codesplashr helper
- DuckDB has no inverse normal function, so there is no geometry SQL for Q–Q plots.