Skip to content
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?

Demo data · seed 20261101 · 60 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. 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.
  2. Points on the curve have the heterozygote share Hardy–Weinberg predicts; points below it have too few heterozygotes, points above too many.
  3. With the band on, a point outside it fails the χ² test at that sample size; compare its colour with the QC verdict.
  1. Callout 1: All heterozygotes (AB) at the apex.
  2. Callout 2: The Hardy–Weinberg parabola.
  3. Callout 3: A marker below the curve: too few heterozygotes.
  4. 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