Skip to content

EProportions · Guide test 295

Hardy–Weinberg chi square test

Compares genotype counts with equilibrium expectations calculated from allele frequencies.

Runs in CodeSplashPython (calls R) example not runR example not run

Do it in CodeSplash

In the app, set it up in Analyze with this method:

In Hardy–Weinberg proportions (exact, χ², likelihood ratio), choose Test = Pearson χ².

Do it in CodeSplash Run this test on your own data, in Python or R.

Bench

Change the design, drag the data, move α. The statistic, its reference distribution and the verdict follow.

Bench · Hardy–Weinberg chi square test

200
0.40
0.15

0 is Hardy–Weinberg equilibrium.

0.050

Your data

Edit the counts
AAAaaa
417683

Dashed lines: the counts H₀ expects (equal shares).

If H₀ were true

χ² = 8.40
  1. The reference: how χ² varies across samples when H₀ is true.
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .004).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

χ2=∑g(Og−Eg)2Eg,E=N(p^2, 2p^q^, q^2), ν=1\chi^2 = \sum_{g}\dfrac{(O_g-E_g)^2}{E_g},\quad E = N\left(\hat p^2,\ 2\hat p\hat q,\ \hat q^2\right),\ \nu = 1

With your numbers

χ2=8.40,p^=0.40\chi^2 = 8.40,\quad \hat p = 0.40
p^\hat p
allele frequency estimated from the genotypes
ν=1\nu = 1
3 classes − 1 − 1 estimated frequency

The verdict

χ²(1) = 8.40, p = .004, F = 0.20

p ≤ α = .050: reject H₀

Effect size: inbreeding coefficient F = 0.205

Deviations flag genotyping error, population structure or inbreeding. Use the exact test when a genotype is rare.

Statistic
8.400
p-value
0.0038
Hardy–Weinberg chi square test on 41, 76, 83 across 3 categories: χ²(1) = 8.40, p = .004, F = 0.20. The p-value is below α = .050, so the data are hard to reconcile with H0.

Hardy–Weinberg chi square test on 41, 76, 83 across 3 categories: χ²(1) = 8.40, p = .004, F = 0.20. The p-value is below α = .050, so the data are hard to reconcile with H₀.

Question and hypotheses

H0: genotype probabilities are p²,2p(1−p),(1−p)².

Assumptions

Independent diploid individuals from a suitably defined population, reliable biallelic genotypes, and random-union-of-gametes Hardy–Weinberg proportions under H0. Relatedness, stratification and genotype error affect inference. Adequate expected genotype counts for chi square calibration.

Formula

p^=2nAA+nAa2NX2=∑g∈{AA,Aa,aa}(Og−Eg)2Eg\begin{gathered}\widehat p=\frac{2n_{AA}+n_{Aa}}{2N}\\[5pt] X^2=\sum_{g\in\{AA,Aa,aa\}}\frac{(O_g-E_g)^2}{E_g}\end{gathered}

Parameters and notation

Eg=N(p̂²,2p̂(1−p̂),(1−p̂)²); usual df=1 after estimating allele frequency.

Structure of the method

Estimate the allele frequency from the three diploid genotype counts, calculate Hardy–Weinberg expected counts, and form Pearson’s discrepancy. Estimating one allele-frequency parameter reduces the usual autosomal biallelic degrees of freedom to one; a three-category generic chi-square calculation with two degrees of freedom is incorrect.

Estimated and nuisance parameters

The allele frequency is a fitted nuisance parameter under equilibrium. Observed counts and total individuals determine genotype expectations. Genotype categories, ploidy and population definition are design/data properties. Multi-allelic and X-chromosome formulations require additional structures rather than reusing the displayed three-cell formula.

Settings and design choices

Specify autosomal versus sex-linked marker, allele coding, population strata, genotype quality filters and continuity correction. The baseline explicitly uses cc=0 because the package otherwise applies a correction. Rare-allele expected counts should trigger consideration of an exact test rather than arbitrary continuity corrections.

Fitting and adaptation

No neural adaptation applies. Refit allele frequency for each tested population/marker under the specified null. If a parametric bootstrap is used, simulate equilibrium genotypes and re-estimate the allele frequency in every replicate. Genome-wide screening also requires an explicit multiplicity strategy.

Sensitivity and robustness

Rare homozygotes, relatedness, population mixture, nonrandom missing genotypes and calling errors affect calibration and interpretation. Departures can arise from several mechanisms besides selection. Report allele frequency, observed/expected counts and quality-control context; nonsignificance can merely reflect low power at a rare marker.

How to use and calibrate

Use χ²1 approximately; exact methods are preferable with rare alleles or sparse expected homozygotes.

Example application

Check genotype quality or population-model compatibility at a marker.

Interpretation and pitfalls

Watch out

Deviation does not uniquely identify selection: population mixture, relatives and genotyping errors can also explain it.

What changed in edition 2

  • New sections: structure of the method, estimated and nuisance parameters, settings and design choices, fitting and adaptation, sensitivity and robustness.

Python and R

Genotype counts from unrelated diploid individuals at one biallelic locus; allele frequency is estimated from these counts. Stratification, relatedness and genotyping error affect interpretation.

Python · invokes R

Not run — Python launcher syntax checked; R backend runtime not verified · needs Python standard library + Rscript; R packages: HardyWeinberg

# Python launcher for the complete R implementation below.
# Requires Rscript on PATH and the listed R packages.
import shutil
import subprocess
rscript = shutil.which("Rscript")
if rscript is None:
    raise RuntimeError("Install R and make Rscript available on PATH.")
r_code = r"""
counts<-c(AA=36,AB=48,BB=16);print(HardyWeinberg::HWChisq(counts,cc=0))
"""
# No shell interpolation. A failed R execution raises an error in Python.
result = subprocess.run([rscript, "--vanilla", "-"], input=r_code,
                        text=True, capture_output=True)
print(result.stdout)
if result.stderr:
    print(result.stderr)
result.check_returncode()
R

Not run — Syntax checked; runtime not verified in the final environment · needs HardyWeinberg

counts<-c(AA=36,AB=48,BB=16);print(HardyWeinberg::HWChisq(counts,cc=0))

Sources

Statistics guide v4 (historical):
Python: Python launcher syntax checked; R backend runtime not verified · R: Syntax checked; runtime not verified in the final environment
Reference's record:
Edition 2 review: Python: skip · R: not executed (Rscript unavailable); why not run: Python: Python-to-R bridge; Rscript is unavailable. R code was not executed. Python: Not run in the reference's review: Python-to-R bridge; Rscript is unavailable. R code was not executed. R: Reviewed but not run: R wasn't available to the reference's authors.

From the CodeSplash statistics guide (v4), entry 295, updated from the reference's edition 2 (reviewed 14 November 2026) as STAT295.