svgdefinetti
De Finetti diagram (genotype frequencies)
Do the markers' genotype frequencies sit on the Hardy–Weinberg curve, or do some have too few or too many heterozygotes?
How to read it
- Read each point as one marker: its distance from each corner shows its share of AA, AB and BB, and its left–right place is the allele frequency.
- Points on the curve have the heterozygote share Hardy–Weinberg predicts; points below it have too few heterozygotes, points above too many.
- With the band on, a point outside it fails the χ² test at that sample size; compare its colour with the QC verdict.
- Callout 1: All heterozygotes (AB) at the apex.
- Callout 2: The Hardy–Weinberg parabola.
- Callout 3: A marker below the curve: too few heterozygotes.
- Callout 4: The AA corner: no copies of the second allele.
Watch out
- A heterozygote deficit across many markers is more often mixed ancestry, inbreeding or a calling problem than selection.
- The band depends on n: with thousands of people tiny, harmless departures fall outside it; read the effect (distance from the curve) as well.
Defaults
- Hardy–Weinberg curve
- On
- Draws the parabola AB = 2q(1 − q) where markers in equilibrium fall.
- Band for sample size
- 0
- People per marker for the χ² acceptance band (0 hides the band).
- Range 0 to 10,000,000, step 10
- Band level (α)
- 0.05
- Markers outside the band fail the 1-df χ² test of Hardy–Weinberg at this α.
- Range 0.0001 to 0.5, step 0.005
Pinned in the code
- Draws the genetics method's published numbers as given (codesplash ≡ codesplashr); only the labelled reference curves are computed for display.
- Each row is normalised by its own total, so counts and shares both work; rows with a missing or negative count, or a zero total, are left out.
- AA sits at the bottom left, BB at the bottom right and AB at the apex; the x position is the second allele's frequency q = BB + AB/2.
- The parabola is AB = 2q(1 − q). The band is AB = 2q(1 − q)(1 ± √(c/n)), c the upper-α χ²₁ quantile, since X² = n D² / (pq)² with D = AA − p² (Cannings & Edwards 1968).
Use with care
Research use only: genotype charts describe a sample; they are not a clinical or diagnostic result.
# De Finetti diagram (genotype frequencies) — Codesplash Chart Lab (recipe "definetti")
# controls: parabola=true, n=0, alpha=0.05
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("definetti-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["HWE"] = pd.Categorical(df["HWE"].astype("string"), categories=["passes", "fails HWE"])
_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")
def freq_levels(s, k=8):
"""Declared level order when the column is categorical, else by descending count (ties A→Z)."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(v) for v in s.cat.categories][:k]
vc = s.dropna().astype(str).value_counts()
return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
AA = "AA"
AB = "AB"
BB = "BB"
LABEL = "marker"
GROUP = "HWE"
N_BAND, ALPHA, PARABOLA = 0, 0.05, True # band sample size (0 = no band), band level, Hardy–Weinberg curve
H = np.sqrt(3) / 2 # apex height: AA at (0, 0), BB at (1, 0), AB at (½, H)
cnt = df[[AA, AB, BB]].apply(pd.to_numeric, errors="coerce")
tot = cnt.sum(axis=1, skipna=False)
keep = (cnt >= 0).all(axis=1) & (tot > 0) # missing, negative or all-zero rows are left out
d, cnt, tot = df[keep], cnt[keep], tot[keep]
x = (cnt[BB] + cnt[AB] / 2) / tot # frequency of the second allele
y = H * cnt[AB] / tot
q = np.linspace(0, 1, 121)
het = 2 * q * (1 - q) # Hardy–Weinberg heterozygote share
groups = freq_levels(d[GROUP], 50) if GROUP else [None]
fig, ax = plt.subplots(figsize=(7, 6.2))
ax.plot([0, 1, 0.5, 0], [0, 0, H, 0], color=REF, linewidth=1)
if N_BAND > 0:
k = np.sqrt(stats.chi2.isf(ALPHA, 1) / N_BAND) # X² = n D² / (pq)² → AB = 2pq(1 ± √(c/n)) (Cannings & Edwards 1968)
lo, hi = np.maximum(0, het * (1 - k)), np.minimum(het * (1 + k), 2 * np.minimum(q, 1 - q))
ax.fill_between(q, H * lo, H * hi, color=PALETTE[0], alpha=0.16, linewidth=0, label=f"{100 * (1 - ALPHA):g}% χ² band, n = {N_BAND}")
if PARABOLA:
ax.plot(q, H * het, color=REF, linewidth=1.4, label="Hardy–Weinberg")
for i, g in enumerate(groups):
m = (d[GROUP].astype(str) == g).to_numpy() if GROUP else np.ones(len(d), bool)
ax.scatter(x[m], y[m], s=18, color=PALETTE[i % len(PALETTE)], alpha=0.85, edgecolors="white", linewidths=0.5, label=g)
if LABEL and len(d) <= 12:
for xi, yi, name in zip(x, y, d[LABEL].astype(str)):
ax.annotate(name, (xi, yi), xytext=(5, 0), textcoords="offset points", va="center", fontsize=8)
ax.text(-0.03, 0, AA, ha="right", va="center", fontweight="bold")
ax.text(1.03, 0, BB, ha="left", va="center", fontweight="bold")
ax.text(0.5, H + 0.03, AB, ha="center", va="bottom", fontweight="bold")
ax.set_aspect("equal")
ax.set_xlim(-0.18, 1.18)
ax.set_ylim(-0.08, H + 0.12)
ax.set_xticks([0, 0.25, 0.5, 0.75, 1])
ax.set_yticks([])
for side in ("left", "right", "top"):
ax.spines[side].set_visible(False)
ax.set_xlabel("frequency of the second allele")
if ax.get_legend_handles_labels()[0]:
ax.legend(frameon=False, loc="upper left")
plt.show()Needs pandas, numpy, matplotlib, scipy · reads definetti-demo.csv · app theme from the optional codesplash helper
# De Finetti diagram (genotype frequencies) — Codesplash Chart Lab (recipe "definetti")
# controls: parabola=true, n=0, alpha=0.05
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("definetti-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["HWE"] = pd.Categorical(df["HWE"].astype("string"), categories=["passes", "fails HWE"])
_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")
def freq_levels(s, k=8):
"""Declared level order when the column is categorical, else by descending count (ties A→Z)."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(v) for v in s.cat.categories][:k]
vc = s.dropna().astype(str).value_counts()
return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
AA = "AA"
AB = "AB"
BB = "BB"
LABEL = "marker"
GROUP = "HWE"
N_BAND, ALPHA, PARABOLA = 0, 0.05, True # band sample size (0 = no band), band level, Hardy–Weinberg curve
H = np.sqrt(3) / 2 # apex height: AA at (0, 0), BB at (1, 0), AB at (½, H)
cnt = df[[AA, AB, BB]].apply(pd.to_numeric, errors="coerce")
tot = cnt.sum(axis=1, skipna=False)
keep = (cnt >= 0).all(axis=1) & (tot > 0) # missing, negative or all-zero rows are left out
d, cnt, tot = df[keep], cnt[keep], tot[keep]
x = (cnt[BB] + cnt[AB] / 2) / tot # frequency of the second allele
y = H * cnt[AB] / tot
q = np.linspace(0, 1, 121)
het = 2 * q * (1 - q) # Hardy–Weinberg heterozygote share
groups = freq_levels(d[GROUP], 50) if GROUP else [None]
fig = go.Figure()
fig.add_scatter(x=[0, 1, 0.5, 0], y=[0, 0, H, 0], mode="lines", line=dict(color=REF, width=1), showlegend=False, hoverinfo="skip")
if N_BAND > 0:
k = np.sqrt(stats.chi2.isf(ALPHA, 1) / N_BAND) # AB = 2pq(1 ± √(c/n)) (Cannings & Edwards 1968)
lo, hi = np.maximum(0, het * (1 - k)), np.minimum(het * (1 + k), 2 * np.minimum(q, 1 - q))
fig.add_scatter(x=np.r_[q, q[::-1]], y=np.r_[H * hi, (H * lo)[::-1]], fill="toself", mode="none", fillcolor=PALETTE[0], opacity=0.2, name=f"{100 * (1 - ALPHA):g}% χ² band, n = {N_BAND}")
if PARABOLA:
fig.add_scatter(x=q, y=H * het, mode="lines", line=dict(color=REF, width=1.5), name="Hardy–Weinberg")
for i, g in enumerate(groups):
m = (d[GROUP].astype(str) == g).to_numpy() if GROUP else np.ones(len(d), bool)
text = d[LABEL].astype(str)[m] if LABEL else None
fig.add_scatter(x=x[m], y=y[m], mode="markers", text=text, name=g or "markers", marker=dict(color=PALETTE[i % len(PALETTE)], size=7, opacity=0.85, line=dict(color="white", width=0.5)))
for tx, ty, name, anchor in ((-0.03, 0, AA, "right"), (1.03, 0, BB, "left"), (0.5, H + 0.04, AB, "center")):
fig.add_annotation(x=tx, y=ty, text=f"<b>{name}</b>", showarrow=False, xanchor=anchor)
fig.update_layout(xaxis=dict(range=[-0.18, 1.18], tickvals=[0, 0.25, 0.5, 0.75, 1], title="frequency of the second allele", zeroline=False),
yaxis=dict(range=[-0.08, H + 0.12], scaleanchor="x", visible=False))
fig.show()Needs pandas, numpy, plotly, scipy · reads definetti-demo.csv · app theme from the optional codesplash helper
# De Finetti diagram (genotype frequencies) — Codesplash Chart Lab (recipe "definetti")
# controls: parabola=true, n=0, alpha=0.05
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("definetti-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["marker"]] <- factor(df[["marker"]])
df[["HWE"]] <- factor(df[["HWE"]], levels = c("passes", "fails HWE"))
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
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
aa_col <- "AA"
ab_col <- "AB"
bb_col <- "BB"
label_col <- "marker"
group_col <- "HWE"
n_band <- 0; alpha <- 0.05; parabola <- TRUE # band n (0 = none), level, HWE curve
h <- sqrt(3) / 2 # AA at (0, 0), BB at (1, 0), AB at (1/2, h)
cnt <- sapply(c(aa_col, ab_col, bb_col), function(v) suppressWarnings(as.numeric(df[[v]])))
cnt <- matrix(cnt, ncol = 3)
tot <- rowSums(cnt)
keep <- !is.na(tot) & tot > 0 & rowSums(cnt < 0, na.rm = TRUE) == 0 # missing, negative or all-zero rows are left out
d <- df[keep, , drop = FALSE]; cnt <- cnt[keep, , drop = FALSE]; tot <- tot[keep]
d$x <- (cnt[, 3] + cnt[, 2] / 2) / tot # frequency of the second allele
d$y <- h * cnt[, 2] / tot
d$group <- if (!is.null(group_col)) factor(as.character(d[[group_col]]), levels = freq_levels(d[[group_col]], 50)) else factor("markers")
q <- seq(0, 1, length.out = 121)
het <- 2 * q * (1 - q) # Hardy–Weinberg heterozygote share
p <- ggplot() + geom_path(data = data.frame(x = c(0, 1, 0.5, 0), y = c(0, 0, h, 0)), aes(x, y), colour = ref_col)
if (n_band > 0) {
k <- sqrt(qchisq(alpha, 1, lower.tail = FALSE) / n_band) # AB = 2pq(1 ± sqrt(c/n)) (Cannings & Edwards 1968)
band <- data.frame(q = q, lo = h * pmax(0, het * (1 - k)), hi = h * pmin(het * (1 + k), 2 * pmin(q, 1 - q)))
p <- p + geom_ribbon(data = band, aes(x = q, ymin = lo, ymax = hi), fill = cs_cat[1], alpha = 0.16)
}
if (parabola) p <- p + geom_line(data = data.frame(q = q, y = h * het), aes(q, y), colour = ref_col, linewidth = 0.7)
p <- p + geom_point(data = d, aes(x, y, colour = group), size = 1.8, alpha = 0.85) +
scale_colour_manual(values = cs_cat[seq_len(nlevels(d$group))], name = NULL) +
annotate("text", x = -0.03, y = 0, label = aa_col, hjust = 1, fontface = "bold") +
annotate("text", x = 1.03, y = 0, label = bb_col, hjust = 0, fontface = "bold") +
annotate("text", x = 0.5, y = h + 0.04, label = ab_col, vjust = 0, fontface = "bold") +
scale_x_continuous(breaks = c(0, 0.25, 0.5, 0.75, 1)) +
coord_equal(xlim = c(-0.18, 1.18), ylim = c(-0.05, h + 0.1)) +
labs(x = "frequency of the second allele", y = NULL) + theme_cs +
theme(axis.text.y = element_blank(), panel.grid = element_blank())
if (!is.null(label_col) && nrow(d) <= 12) p <- p + geom_text(data = d, aes(x, y, label = .data[[label_col]]), hjust = -0.25, size = 2.8)
print(p)Needs ggplot2 · reads definetti-demo.csv · app theme from the optional codesplashr helper