Skip to content

ADescribe · normality.shapiro

Normality test (one test)

Is a numeric variable (or each group of it) plausibly normally distributed?

One normality test per group — Shapiro–Wilk by default, or any of the guide's eleven (Shapiro–Francia, Filliben, Anderson–Darling, Lilliefors, Cramér–von Mises, D'Agostino–Pearson, Jarque–Bera, skewness, kurtosis, Pearson χ²) — with skewness and excess kurtosis so large samples are judged by shape rather than by p alone. For all eleven at once use the normality battery.

Verified in Python and R Python and R agree to 6 decimals Seeded Also called Shapiro–Wilk, Shapiro Wilk, shapiro.test…

A real result

Example “Plantgrowth by group”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Shapiro–Wilk normality testRecorded · Python and R agreeRecorded 2026-11-17 · 16 values compared
R

ctrl: W = 0.957, p = .747; trt1: W = 0.930, p = .452; trt2: W = 0.941, p = .564

Groups tested
3
p < .05
0

Plots

Normal Q–Q: weight (ctrl)Is a variable (or a set of residuals) approximately normal, and where does it depart?
View data
weight
4.170
5.580
5.180
6.110
4.500
4.610
5.170
4.530
5.330
5.140
Normal Q–Q: weight (trt1)Is a variable (or a set of residuals) approximately normal, and where does it depart?
View data
weight
4.810
4.170
4.410
3.590
5.870
3.830
6.030
4.890
4.320
4.690
Normal Q–Q: weight (trt2)Is a variable (or a set of residuals) approximately normal, and where does it depart?
View data
weight
6.310
5.120
5.540
5.500
5.370
5.290
4.920
6.150
5.800
5.260

Assumptions

  • Normality — ctrl — W = 0.957, p = .747; skewness 0.32, excess kurtosis -0.23
  • Normality — trt1 — W = 0.930, p = .452; skewness 0.66, excess kurtosis -0.20
  • Normality — trt2 — W = 0.941, p = .564; skewness 0.67, excess kurtosis -0.32

Shapiro–Wilk

groupnWpSkewness (G1)Excess kurtosis (G2)Verdict
ctrl100.9567.7470.3210−0.2291no evidence against normality
trt1100.9304.4520.6590−0.2028no evidence against normality
trt2100.9410.5640.6732−0.3242no evidence against normality
  • A screening test: with large samples tiny departures are significant, with small samples real ones are missed. Check a Q–Q plot.
Python

ctrl: W = 0.957, p = .747; trt1: W = 0.930, p = .452; trt2: W = 0.941, p = .564

Groups tested
3
p < .05
0

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Normality — ctrl — W = 0.957, p = .747; skewness 0.32, excess kurtosis -0.23
  • Normality — trt1 — W = 0.930, p = .452; skewness 0.66, excess kurtosis -0.20
  • Normality — trt2 — W = 0.941, p = .564; skewness 0.67, excess kurtosis -0.32

Shapiro–Wilk

groupnWpSkewness (G1)Excess kurtosis (G2)Verdict
ctrl100.9567.7470.3210−0.2291no evidence against normality
trt1100.9304.4520.6590−0.2028no evidence against normality
trt2100.9410.5640.6732−0.3242no evidence against normality
  • A screening test: with large samples tiny departures are significant, with small samples real ones are missed. Check a Q–Q plot.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Plantgrowth by groupplantgrowth · group: group · outcome: weight
  • Singlemtcars · outcome: mpg
  • Missing valuesairquality · group: month_f · outcome: Ozone
  • Francia ozoneairquality · outcome: Ozone
  • Filliben mpgmtcars · outcome: mpg
  • Cvm plantgrowthplantgrowth · group: group · outcome: weight
  • Chisq ozoneairquality · outcome: Ozone
  • Skewness ozoneairquality · outcome: Ozone

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Assess distribution: histogram, Q–Q · Statistics Guide · A — Describe data
  • Normality tests: Shapiro–Wilk · Statistics Guide · A — Describe data
  • Normality (per group, differences or residuals) · Statistics Guide · Step 2 — Check assumptions

What you need

Variablenumeric · 1 column
The numeric variable to check for normality.
Split bycategorical / boolean · 0–1 column · 1–30 levels
Optional — test each group separately (what t-tests and ANOVA assume).

Choices you make

Options

Testdefault shapiro_wilk

Which normality test to run. Shapiro–Wilk is the most powerful all-rounder for n up to 5,000.

  • Shapiro–Wilk(default) — The default: best overall power for 3–5,000 values.
  • Shapiro–Francia — A simpler Shapiro–Wilk (squared correlation with normal scores); good for heavy tails; 5–5,000 values.
  • Filliben probability-plot correlation — How straight the normal Q–Q plot is (r); p by simulation.
  • Anderson–Darling — Weights the tails heavily; estimated mean and SD; at least 8 values.
  • Lilliefors (Kolmogorov–Smirnov) — The largest gap between the ECDF and the fitted normal; least powerful of the EDF tests.
  • Cramér–von Mises — Squared ECDF gaps summed over the whole range; at least 8 values.
  • D'Agostino–Pearson omnibus (K²) — Combines the skewness and kurtosis z-tests; at least 8 values (20+ preferred).
  • Jarque–Bera — Skewness and kurtosis against a χ²(2); needs large samples to be accurate.
  • D'Agostino skewness — Asymmetry only (z of the sample skewness); at least 8 values.
  • Anscombe–Glynn kurtosis — Tail weight only (z of the sample kurtosis); at least 8 values, rough below 20.
  • Pearson χ² — Counts in equiprobable classes of the fitted normal; weakest of the eleven, kept for the record.

Advanced

Simulationsdefault 1999

Normal samples simulated for Filliben's p (shared seeded stream, same in Python and R).

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Normality

    One row per variable or group: Shapiro–Wilk p below .05 flags data unlikely to come from a normal distribution.

What it reports

n_total
How many independent units the analysis used; it sets precision and power.
n_groups
How many independent units the analysis used; it sets precision and power.
n_tested
How many independent units the analysis used; it sets precision and power.
n_failing
How many independent units the analysis used; it sets precision and power.
p_min
How surprising your data would be if the null hypothesis were true, as a probability.
w_at_min
A test of normality; a small p-value says the data are unlikely to come from a normal distribution.
group_at_min
The group whose test gave the smallest p-value, the strongest sign of non-normality. Empty when there is no grouping.

Per group, level or term: w[<group>], p[<group>], n[<group>], w, p, n without a group

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines call library implementations of Royston's AS R94 (scipy.stats.shapiro, stats::shapiro.test); W and p agree to about 1e-14.
  • The other ten tests come from the shared helpers (codesplash.stats.normality ↔ codesplashr); Filliben's p is Monte Carlo on the shared Wichmann–Hill stream.
Python

The exact script CodeSplash ran for example “Plantgrowth by group” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Normality test (one test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method normality.shapiro 1.2.2 · spec beb816524c520543
# Dataset: plantgrowth (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.stats import normality as csn

# %% Data
df = pd.read_parquet("tests/parity/fixtures/plantgrowth.parquet", columns=["weight", "group"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["ctrl", "trt1", "trt2"])  # stored level order
df = df.dropna(subset=["weight", "group"])  # listwise deletion over the analysis columns
df["group"] = df["group"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["weight", "group"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
y = "weight"
g = "group"
parts = [(str(lv), df.loc[df[g] == lv, y].to_numpy(dtype=float)) for lv in df[g].cat.categories]
if len(df) >= 2 and len(np.unique(df[y].to_numpy(dtype=float))) < 2:  # no variation: no group can be tested
    cs.cs_error("CS_E_CONSTANT", column=y)
alpha = 0.05
test = "shapiro_wilk"
seed, reps = 42, int(1999)  # Filliben's p: normal samples from the shared Wichmann–Hill stream
name, sym = csn.TESTS[test]
NEEDS = {"shapiro_wilk": "3–5,000", "shapiro_francia": "5–5,000", "filliben": "at least 3", "lilliefors": "at least 5", "jarque_bera": "at least 3"}
needs = f"needs {NEEDS.get(test, 'at least 8')} values that are not all equal"
rows, values, assumptions = [], {"n_total": len(df)}, []
for level, x in parts:
    n = len(x)
    suffix = "" if level is None else f"[{level}]"
    res = csn.normality_test(x, test, seed=seed, reps=reps)
    if np.isfinite(res["p"]):
        w, p = res["statistic"], res["p"]
        verdict = "departs from normality" if p < alpha else "no evidence against normality"
    else:
        w = p = None
        verdict = f"not tested ({needs})"
    g1 = float(stats.skew(x, bias=False)) if n > 2 else None
    g2 = float(stats.kurtosis(x, bias=False)) if n > 3 else None
    rows.append({"group": level if level is not None else y, "n": n, "w": w, "p": p, "skewness": g1, "kurtosis": g2, "verdict": verdict})
    values.update({f"w{suffix}": w, f"p{suffix}": p, f"n{suffix}": n})
    status = "info" if p is None else ("warn" if p < alpha else "pass")
    if p is not None and p < alpha and n >= 50:
        status = "info"  # with large n, trivial departures are "significant": judge by shape, not p
    assumptions.append({"key": f"normality{suffix}", "label": f"Normality — {level if level is not None else y}", "status": status,
                        "detail": verdict if p is None else f"{sym} = {w:.3f}, {cs.fmt_p(p)}; skewness {g1:.2f}, excess kurtosis {g2:.2f}" if g2 is not None else f"{sym} = {w:.3f}, {cs.fmt_p(p)}",
                        "statistic": w, "p": p})
    if n > 5000 and test in ("shapiro_wilk", "shapiro_francia"):
        warnings.append(f"{level or y}: more than 5,000 values — {name} is not defined; use a Q–Q plot and skewness/kurtosis, or another test.")

# %% Result
tested = [r for r in rows if r["p"] is not None]
failing = [r for r in tested if r["p"] < alpha]
if not tested:
    summary = f"{name} could not be computed (each group {needs})."
elif len(rows) == 1:
    r = rows[0]
    summary = f"{name} test for {y}: {sym} = {r['w']:.3f}, {cs.fmt_p(r['p'])} (n = {r['n']}) — {r['verdict']}."
else:
    summary = (
        f"{name} test for {y} by {g}: {len(failing)} of {len(tested)} groups depart from normality at α = .05"
        + (f" ({', '.join(r['group'] for r in failing)})." if failing else ".")
    )
low = min(tested, key=lambda r: r["p"]) if tested else None
values.update({
    "n_groups": len(rows), "n_tested": len(tested), "n_failing": len(failing),
    "p_min": None if low is None else low["p"], "w_at_min": None if low is None else low["w"],
    "group_at_min": "" if low is None or g is None else str(low["group"]),
})
charts = [
    cs.chart(f"qq-{i}", "qq", f"Normal Q–Q: {y}" + (f" ({level})" if level is not None else ""), {"x": cs.col(y, x[np.unique(np.round(np.linspace(0, len(x) - 1, min(len(x), 5000))).astype(int))])})
    for i, (level, x) in enumerate(parts[:6]) if len(x) >= 3
]
cs.publish({
    "method": "normality.shapiro",
    "methodVersion": "1.2.2",
    "title": f"{name} normality test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": len(df),
    "summary": summary,
    "apa": "; ".join(f"{r['group']}: {sym} = {r['w']:.3f}, {cs.fmt_p(r['p'])}" for r in tested),
    "statistics": [{"key": "groups", "label": "Groups tested", "value": len(tested)}, {"key": "failing", "label": "p < .05", "value": len(failing)}],
    "tables": [{
        "key": "shapiro", "title": name,
        "columns": [{"key": "group", "label": g or "Variable", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
                    {"key": "w", "label": sym, "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
                    {"key": "skewness", "label": "Skewness (G1)", "type": "number"}, {"key": "kurtosis", "label": "Excess kurtosis (G2)", "type": "number"},
                    {"key": "verdict", "label": "Verdict", "type": "string"}],
        "rows": rows,
    }],
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": ["A screening test: with large samples tiny departures are significant, with small samples real ones are missed. Check a Q–Q plot."]
             + ([f"Filliben's p compares r with {reps} simulated normal samples of the same size (seed {seed})."] if test == "filliben" else []),
    "charts": charts,
    "values": values,
})
R

The exact script CodeSplash ran for example “Plantgrowth by group” · R version 4.5.1 (2025-06-13)

# Normality test (one test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method normality.shapiro 1.2.2 · spec beb816524c520543
# Dataset: plantgrowth (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/plantgrowth.parquet", col_select = c("weight", "group")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("ctrl", "trt1", "trt2"))  # stored level order
df <- df[stats::complete.cases(df[c("weight", "group")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("weight", "group"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
y <- "weight"
g <- "group"
parts <- lapply(levels(df[[g]]), function(lv) list(level = lv, x = df[[y]][df[[g]] == lv]))
if (nrow(df) >= 2 && length(unique(df[[y]])) < 2) cs_error("CS_E_CONSTANT", column = y)  # no variation: no group can be tested
alpha <- 0.05
test <- "shapiro_wilk"
seed <- 42  # Filliben's p: normal samples from the shared Wichmann-Hill stream
reps <- as.integer(1999)
tinfo <- cs_normality_test(numeric(0), test)
name <- tinfo$label
sym <- tinfo$symbol
needs_n <- switch(test, shapiro_wilk = "3–5,000", shapiro_francia = "5–5,000", filliben = "at least 3", lilliefors = "at least 5", jarque_bera = "at least 3", "at least 8")
needs <- sprintf("needs %s values that are not all equal", needs_n)
G1 <- function(x) {
  n <- length(x)
  m <- mean(x)
  sqrt(n * (n - 1)) / (n - 2) * mean((x - m)^3) / mean((x - m)^2)^1.5
}
G2 <- function(x) {
  n <- length(x)
  m <- mean(x)
  ((n + 1) * (mean((x - m)^4) / mean((x - m)^2)^2 - 3) + 6) * (n - 1) / ((n - 2) * (n - 3))
}
rows <- list()
values <- list(n_total = nrow(df))
assumptions <- list()
for (part in parts) {
  x <- part$x
  n <- length(x)
  label <- if (is.null(part$level)) y else part$level
  suffix <- if (is.null(part$level)) "" else sprintf("[%s]", part$level)
  res <- cs_normality_test(x, test, seed = seed, reps = reps)
  if (is.finite(res$p)) {
    w <- res$statistic
    p <- res$p
    verdict <- if (p < alpha) "departs from normality" else "no evidence against normality"
  } else {
    w <- NULL
    p <- NULL
    verdict <- sprintf("not tested (%s)", needs)
  }
  g1 <- if (n > 2) G1(x) else NULL
  g2 <- if (n > 3) G2(x) else NULL
  rows[[length(rows) + 1]] <- list(group = label, n = n, w = w, p = p, skewness = g1, kurtosis = g2, verdict = verdict)
  values[paste0("w", suffix)] <- list(w)
  values[paste0("p", suffix)] <- list(p)
  values[[paste0("n", suffix)]] <- n
  status <- if (is.null(p)) "info" else if (p < alpha) "warn" else "pass"
  if (!is.null(p) && p < alpha && n >= 50) status <- "info"  # with large n, judge by shape, not p
  detail <- if (is.null(p)) verdict else if (!is.null(g2)) {
    sprintf("%s = %.3f, %s; skewness %.2f, excess kurtosis %.2f", sym, w, cs_fmt_p(p), g1, g2)
  } else {
    sprintf("%s = %.3f, %s", sym, w, cs_fmt_p(p))
  }
  assumptions[[length(assumptions) + 1]] <- list(key = paste0("normality", suffix), label = paste("Normality —", label),
                                                 status = status, detail = detail, statistic = w, p = p)
  if (n > 5000 && test %in% c("shapiro_wilk", "shapiro_francia")) {
    warnings <- c(warnings, sprintf("%s: more than 5,000 values — %s is not defined; use a Q–Q plot and skewness/kurtosis, or another test.", label, name))
  }
}

# %% Result
tested <- Filter(function(r) !is.null(r$p), rows)
failing <- Filter(function(r) r$p < alpha, tested)
summary <- if (!length(tested)) {
  sprintf("%s could not be computed (each group %s).", name, needs)
} else if (length(rows) == 1) {
  r <- rows[[1]]
  sprintf("%s test for %s: %s = %.3f, %s (n = %d) — %s.", name, y, sym, r$w, cs_fmt_p(r$p), r$n, r$verdict)
} else {
  paste0(sprintf("%s test for %s by %s: %d of %d groups depart from normality at α = .05", name, y, g, length(failing), length(tested)),
         if (length(failing)) sprintf(" (%s).", paste(vapply(failing, `[[`, "", "group"), collapse = ", ")) else ".")
}
low <- if (length(tested)) tested[[which.min(vapply(tested, function(r) r$p, numeric(1)))]] else NULL
values$n_groups <- length(rows)
values$n_tested <- length(tested)
values$n_failing <- length(failing)
values["p_min"] <- list(if (is.null(low)) NULL else low$p)  # null (not missing) when nothing was tested
values["w_at_min"] <- list(if (is.null(low)) NULL else low$w)
values$group_at_min <- if (is.null(low) || is.null(g)) "" else as.character(low$group)
charts <- list()
for (i in seq_len(min(6, length(parts)))) {
  x <- parts[[i]]$x
  if (length(x) < 3) next
  rows_c <- unique(round(seq(1, length(x), length.out = min(length(x), 5000))))
  lv <- parts[[i]]$level
  charts[[length(charts) + 1]] <- cs_chart(sprintf("qq-%d", i - 1), "qq", paste0("Normal Q–Q: ", y, if (!is.null(lv)) sprintf(" (%s)", lv) else ""),
                                           list(x = cs_col(y, x[rows_c])))
}
cs_publish(list(
  method = "normality.shapiro",
  methodVersion = "1.2.2",
  title = paste(name, "normality test"),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = nrow(df),
  summary = summary,
  apa = paste(vapply(tested, function(r) sprintf("%s: %s = %.3f, %s", r$group, sym, r$w, cs_fmt_p(r$p)), ""), collapse = "; "),
  statistics = list(list(key = "groups", label = "Groups tested", value = length(tested)), list(key = "failing", label = "p < .05", value = length(failing))),
  tables = list(list(
    key = "shapiro", title = name,
    columns = list(list(key = "group", label = if (is.null(g)) "Variable" else g, type = "string"), list(key = "n", label = "n", type = "integer"),
                   list(key = "w", label = sym, type = "number"), list(key = "p", label = "p", type = "pvalue"),
                   list(key = "skewness", label = "Skewness (G1)", type = "number"), list(key = "kurtosis", label = "Excess kurtosis (G2)", type = "number"),
                   list(key = "verdict", label = "Verdict", type = "string")),
    rows = rows
  )),
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = c(list("A screening test: with large samples tiny departures are significant, with small samples real ones are missed. Check a Q–Q plot."),
            if (test == "filliben") list(sprintf("Filliben's p compares r with %d simulated normal samples of the same size (seed %d).", reps, as.integer(seed))) else list()),
  charts = charts,
  values = values
))

Sources

  • Shapiro, S. S., & Wilk, M. B. (1965). An analysis of variance test for normality. Biometrika, 52, 591–611.
  • Royston, P. (1995). Remark AS R94: A remark on algorithm AS 181. Applied Statistics, 44, 547–551.
  • Royston, P. (1993). A pocket-calculator algorithm for the Shapiro–Francia test for non-normality. Statistics in Medicine, 12, 181–184.
  • Filliben, J. J. (1975). The probability plot correlation coefficient test for normality. Technometrics, 17, 111–117.
  • Stephens, M. A. (1986). Tests based on EDF statistics. In D'Agostino & Stephens (Eds.), Goodness-of-fit techniques.

From the CodeSplash method registry · normality.shapiro v1.2.2.