One peak or more?
Hartigan's dip test and the bimodality coefficient, what they say about peaks, and why they can't count the groups behind your data.
What runs in CodeSplash
- STAT127Hartigan dip test Runs in CodeSplash
- Modality (Hartigan's dip test) Verified in Python and R
You will be able to
- Explain what the dip statistic measures
- Read a dip result together with the bimodality coefficient
- Explain why one peak doesn't show one population
Read first
How many peaks?
ReadA column with two peaks changes everything you might say about it. The mean sits in a place almost no values reach, and a single model fits nothing well.
A histogram might show peaks, but it depends on your choice of bins. The dip testHartigan's dip testTests whether a distribution has a single peak; a small p-value suggests two or more groups mixed together. doesn't use bins.
Old Faithful
PredictPredict first
Eruption durations at Old Faithful, for 272 eruptions, look strongly two-peaked in a histogram.
Roughly what p-value would you expect from a test of one peak? Drag to your guess.
Make your guess between 0 and 1 p-value, then reveal.
Reveal
Very small: dip = 0.092, p = .002. With 499 uniform samples, that's the smallest p the simulation can give.
What the dip measures
ReadAny one-peaked distribution has a CDF that bends one way, then the other, with one turning point. Two peaks need more bends.
The dip is the smallest distance you can get between your ECDF and any one-peaked CDF. Larger means further from one peak.
The null is the uniform distribution, which is the hardest one-peaked case to tell from several peaks. That makes the test conservative for other single-peaked shapes, and small dips are easy to miss.
Hartigan's dip test, D = 0.092, p = .002
- Dip D
- 0.0924
- p
- 0.0020
- Bimodality coefficient
- 0.7692
Plots
View data
| eruptions |
|---|
| 3.600 |
| 1.800 |
| 3.333 |
| 2.283 |
| 4.533 |
| 2.883 |
| 4.700 |
| 3.600 |
| 1.950 |
| 4.350 |
| 1.833 |
| 3.917 |
| 4.200 |
| 1.750 |
| 4.700 |
| 2.167 |
| 1.750 |
| 4.800 |
| 1.600 |
| 4.250 |
| 1.800 |
| 1.750 |
| 3.450 |
| 3.067 |
| 4.533 |
| 3.600 |
| 1.967 |
| 4.083 |
| 3.850 |
| 4.433 |
| 4.300 |
| 4.467 |
| 3.367 |
| 4.033 |
| 3.833 |
| 2.017 |
| 1.867 |
| 4.833 |
| 1.833 |
| 4.783 |
| 4.350 |
| 1.883 |
| 4.567 |
| 1.750 |
| 4.533 |
| 3.317 |
| 3.833 |
| 2.100 |
| 4.633 |
| 2 |
| 4.800 |
| 4.716 |
| 1.833 |
| 4.833 |
| 1.733 |
| 4.883 |
| 3.717 |
| 1.667 |
| 4.567 |
| 4.317 |
First 60 of 272 rows.
Assumptions
- Continuous values — The dip assumes a continuous variable; many ties (rounding, counts) make modes hard to judge.
Modality
| Measure | Value | Reading |
|---|---|---|
| Hartigan's dip D | 0.0924 | more than one mode (p < .05) |
| p (uniform null) | 0.0020 | 499 simulations |
| Sarle's bimodality coefficient | 0.7692 | above 5/9: possibly bimodal |
| Skewness (G1) | −0.4182 | |
| Excess kurtosis (G2) | −1.506 |
- The dip is the largest distance between the data's ECDF and the closest unimodal distribution; its p-value compares it with uniform samples of the same size (the least favorable unimodal case, so the test is conservative).
- Sarle's coefficient is a screening heuristic from skewness and kurtosis, not a test; heavy skew alone can push it above 5/9.
- 146 tied value(s): ties are treated as infinitesimally separated (as diptest does).
The exact R script · R R version 4.5.1 (2025-06-13)
# Modality (Hartigan's dip test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.modality 1.0.1 · spec a3a1987b3f540f5d
# Dataset: h_faithful (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/h_faithful.parquet", col_select = c("eruptions")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("eruptions")]), , 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("eruptions")) # infinite values stop the run (registry/errors.yaml)
# %% Test
y <- "eruptions"
x <- as.numeric(df[[y]])
x <- x[is.finite(x)]
n <- length(x)
seed <- 42 # uniform null samples from the shared Wichmann-Hill stream
reps <- as.integer(499)
alpha <- 0.05
if (n < 4) cs_error("CS_E_TOO_FEW_ROWS", what = "The dip test", min = 4, n = n)
if (length(unique(x)) < 2) cs_error("CS_E_CONSTANT", column = y) # one value: no distribution shape to judge, and skewness and kurtosis are 0 / 0
dt <- cs_dip_test(x, reps = reps, seed = seed)
d <- dt[1]
p <- dt[2]
bcv <- cs_bimodality_coefficient(x)
bc <- bcv[1]
bc_flag <- is.finite(bc) && bc > 5 / 9
ties <- n - length(unique(x))
# %% Result
values <- list(n = n, dip = d, p = p, bc = bc, bc_flag = bc_flag, skewness = bcv[2], kurtosis = bcv[3], reps = reps, ties = ties)
multi <- p < alpha
summary <- paste0(sprintf("Hartigan's dip for %s: D = %.4f, %s (%d uniform samples, seed %d) — ", y, d, cs_fmt_p(p), reps, as.integer(seed)),
if (multi) "evidence of more than one mode." else "no evidence against a single mode.",
if (is.finite(bc)) sprintf(" Sarle's bimodality coefficient is %.3f, %s the 5/9 ≈ 0.556 benchmark.", bc, if (bc_flag) "above" else "below") else "")
notes <- list("The dip is the largest distance between the data's ECDF and the closest unimodal distribution; its p-value compares it with uniform samples of the same size (the least favorable unimodal case, so the test is conservative).",
"Sarle's coefficient is a screening heuristic from skewness and kurtosis, not a test; heavy skew alone can push it above 5/9.")
if (ties > 0) notes[[length(notes) + 1]] <- sprintf("%d tied value(s): ties are treated as infinitesimally separated (as diptest does).", as.integer(ties))
cs_publish(list(
method = "distribution.modality",
methodVersion = "1.0.1",
title = "Modality — Hartigan's dip test",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("Hartigan's dip test, D = %.3f, %s", d, cs_fmt_p(p)),
statistics = list(list(key = "dip", label = "Dip D", value = d), list(key = "p", label = "p", value = p), list(key = "bc", label = "Bimodality coefficient", value = bc)),
tables = list(list(key = "modality", title = "Modality", columns = list(
list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "reading", label = "Reading", type = "string")), rows = list(
list(measure = "Hartigan's dip D", value = d, reading = if (multi) "more than one mode (p < .05)" else "consistent with one mode"),
list(measure = "p (uniform null)", value = p, reading = sprintf("%d simulations", reps)),
list(measure = "Sarle's bimodality coefficient", value = bc, reading = if (bc_flag) "above 5/9: possibly bimodal" else "below 5/9"),
list(measure = "Skewness (G1)", value = bcv[2], reading = ""), list(measure = "Excess kurtosis (G2)", value = bcv[3], reading = "")))),
effectSizes = list(),
assumptions = list(list(key = "continuous", label = "Continuous values", status = if (ties > n %/% 4) "warn" else "info",
detail = "The dip assumes a continuous variable; many ties (rounding, counts) make modes hard to judge.")),
warnings = warnings,
notes = notes,
charts = list(cs_chart("hist", "histogram", sprintf("Distribution of %s", y), list(x = cs_col(y, x)), controls = list(kde = TRUE))),
values = values
))
Hartigan's dip test, D = 0.092, p = .002
- Dip D
- 0.0924
- p
- 0.0020
- Bimodality coefficient
- 0.7692
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Continuous values — The dip assumes a continuous variable; many ties (rounding, counts) make modes hard to judge.
Modality
| Measure | Value | Reading |
|---|---|---|
| Hartigan's dip D | 0.0924 | more than one mode (p < .05) |
| p (uniform null) | 0.0020 | 499 simulations |
| Sarle's bimodality coefficient | 0.7692 | above 5/9: possibly bimodal |
| Skewness (G1) | −0.4182 | |
| Excess kurtosis (G2) | −1.506 |
- The dip is the largest distance between the data's ECDF and the closest unimodal distribution; its p-value compares it with uniform samples of the same size (the least favorable unimodal case, so the test is conservative).
- Sarle's coefficient is a screening heuristic from skewness and kurtosis, not a test; heavy skew alone can push it above 5/9.
- 146 tied value(s): ties are treated as infinitesimally separated (as diptest does).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Modality (Hartigan's dip test)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.modality 1.0.1 · spec a3a1987b3f540f5d
# Dataset: h_faithful (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import distribution as csd
# %% Data
df = pd.read_parquet("tests/parity/fixtures/h_faithful.parquet", columns=["eruptions"])
n_input = len(df)
df = df.dropna(subset=["eruptions"]) # listwise deletion over the analysis columns
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, ["eruptions"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
y = "eruptions"
x = df[y].to_numpy(dtype=float)
x = x[np.isfinite(x)]
n = x.size
seed, reps = 42, int(499) # uniform null samples from the shared Wichmann–Hill stream
alpha = 0.05
if n < 4:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="The dip test", min=4, n=n)
if len(np.unique(x)) < 2: # one value: no distribution shape to judge, and skewness and kurtosis are 0 / 0
cs.cs_error("CS_E_CONSTANT", column=y)
d, p = csd.dip_test(x, reps=reps, seed=seed)
bc, g1, g2 = csd.bimodality_coefficient(x)
bc_flag = bool(np.isfinite(bc) and bc > 5 / 9)
ties = int(n - np.unique(x).size)
# %% Result
values = {"n": n, "dip": d, "p": p, "bc": bc, "bc_flag": bc_flag, "skewness": g1, "kurtosis": g2, "reps": reps, "ties": ties}
multi = p < alpha
summary = (f"Hartigan's dip for {y}: D = {d:.4f}, {cs.fmt_p(p)} ({reps} uniform samples, seed {seed}) — "
+ ("evidence of more than one mode." if multi else "no evidence against a single mode.")
+ (f" Sarle's bimodality coefficient is {bc:.3f}, {'above' if bc_flag else 'below'} the 5/9 ≈ 0.556 benchmark." if np.isfinite(bc) else ""))
notes = ["The dip is the largest distance between the data's ECDF and the closest unimodal distribution; its p-value compares it with uniform samples of the same size (the least favorable unimodal case, so the test is conservative).",
"Sarle's coefficient is a screening heuristic from skewness and kurtosis, not a test; heavy skew alone can push it above 5/9."]
if ties:
notes.append(f"{ties} tied value(s): ties are treated as infinitesimally separated (as diptest does).")
cs.publish({
"method": "distribution.modality",
"methodVersion": "1.0.1",
"title": "Modality — Hartigan's dip test",
"engine": cs.engine_info("pandas", "numpy"),
"n": n,
"summary": summary,
"apa": f"Hartigan's dip test, D = {d:.3f}, {cs.fmt_p(p)}",
"statistics": [{"key": "dip", "label": "Dip D", "value": d}, {"key": "p", "label": "p", "value": p}, {"key": "bc", "label": "Bimodality coefficient", "value": bc}],
"tables": [{"key": "modality", "title": "Modality", "columns": [
{"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "reading", "label": "Reading", "type": "string"}], "rows": [
{"measure": "Hartigan's dip D", "value": d, "reading": "more than one mode (p < .05)" if multi else "consistent with one mode"},
{"measure": "p (uniform null)", "value": p, "reading": f"{reps} simulations"},
{"measure": "Sarle's bimodality coefficient", "value": bc, "reading": "above 5/9: possibly bimodal" if bc_flag else "below 5/9"},
{"measure": "Skewness (G1)", "value": g1, "reading": ""}, {"measure": "Excess kurtosis (G2)", "value": g2, "reading": ""}]}],
"effectSizes": [],
"assumptions": [{"key": "continuous", "label": "Continuous values", "status": "warn" if ties > n // 4 else "info",
"detail": "The dip assumes a continuous variable; many ties (rounding, counts) make modes hard to judge."}],
"warnings": warnings,
"notes": notes,
"charts": [cs.chart("hist", "histogram", f"Distribution of {y}", {"x": cs.col(y, x)}, controls={"kde": True})],
"values": values,
})
Pull the humps apart
ExploreSet the distance between the two humps to about 2 SDs, then 3, and try different numbers of bins. When do you first see two peaks? Does that depend on the bins?
AExplorable · Bins and bandwidth
How do histogram bins and smoothing bandwidth change the story the same data tell?
How many humps does the population really have?
Bars: histogram with your bins. Line: kernel density with your bandwidth.
Commit your prediction above to see the result
Make your prediction to see the result.
An equal mix of two normals with the same spread has one peak until their means are more than 2 SDs apart.
A one-peaked column
ReadA roughly normal column of 80 values gives dip = 0.040, p = .422.
The card also reports Sarle's bimodality coefficient. It's calculated from skewness and kurtosis, and a value above flags a possible second peak. It's a screen rather than a test:
- Old Faithful: 0.77.
- This column: 0.34.
Heavy skew alone can also lift the coefficient.
Rounded data
PredictPredict first
Measurements rounded to whole numbers make stacks of ties. Eruptions have 146 ties.
How might heavy rounding affect a dip test?
Reveal
They could create false peaks, because each stack is a small step in the ECDF. Check by adding a little jitter, or test on the unrounded values. Another column here has 19 ties, and it gives no sign of more than one peak: p = .897.
One peak, many groups?
ReflectYour customers' spend gives a dip test with a large p-value. A colleague says that means there's one kind of customer.
Is that a fair reading? Think back to the explorable: what would two groups with close means look like? What would you check instead?
Check your understanding
CheckpointCheck yourself
What does a small dip-test p-value suggest?
Show the answer
Answer: a
The dip test sets a single peak against anything else. It doesn't count peaks or groups. Look at the shape, and find what separates them.
Check yourself
A simulated dip p-value uses 499 uniform samples. What is the smallest p it can report? Use .
Show the answer
Answer: 0.002
. Use more samples if the floor gets in the way.
Check yourself
An equal mix of two normal groups with the same SD has means 1.5 SDs apart. How many peaks does its density have?
Show the answer
Answer: a
Two peaks need the means to be more than 2 SDs apart when the groups are equal and the SDs match. So real groups can be hidden under one peak.
Do it in CodeSplash
In the appRun it on any numeric column. If it rejects, look for a variable that separates the peaks, then analyze the groups instead of the mix.
This script reproduces the bimodality coefficient for Old Faithful, 0.769. For the dip itself, use the diptest package.
import pandas as pd
from scipy import stats
x = pd.read_csv("h_faithful.csv")["eruptions"]
n = len(x)
g = stats.skew(x, bias=False)
k = stats.kurtosis(x, bias=False)
print((g**2 + 1) / (k + 3 * (n - 1) ** 2 / ((n - 2) * (n - 3))))x <- read.csv("h_faithful.csv")$eruptions
n <- length(x)
z <- (x - mean(x)) / sd(x)
g <- n / ((n - 1) * (n - 2)) * sum(z^3)
k <- n * (n + 1) / ((n - 1) * (n - 2) * (n - 3)) * sum(z^4) -
3 * (n - 1)^2 / ((n - 2) * (n - 3))
(g^2 + 1) / (k + 3 * (n - 1)^2 / ((n - 2) * (n - 3)))Recap
Recap- The dip test measures how far your ECDF sits from the closest one-peaked CDF, with no bins.
- It's conservative, and it can't count groups.
- The bimodality coefficient is a quick screen, and skew can lift it.
- One peak doesn't show one population, and heavy rounding can mislead.
Concepts in this lesson