Chi-Square Goodness-of-Fit Test
Nonparametric Tests
Does the sample follow the distribution you claim?
The goodness-of-fit test answers a single question: when you count how often each category occurred, are those counts consistent with a distribution you specified in advance? A die that should be fair, a product mix that marketing predicted, a gene that genetics says should segregate three-to-one β each is a claim about expected frequencies, and each can be checked by comparing the claim against what you actually counted.
The test works entirely on counts, not on the raw values, which is why it handles data that no t-test would touch. It is also one of the few tests where you can compute the answer by hand with a calculator, and understanding that arithmetic is what makes the assumptions and failure modes obvious rather than magical.
- Compare observed category counts against expected counts from a stated model.
- Works for any number of categories and any hypothesised distribution.
- Sensitive to small expected counts, which is where the real skill lies.
The intuition behind the statistic
Start with the difference between observed and expected for one category. If a fair six-sided die is rolled six hundred times, you expect one hundred occurrences of each face. A face that shows up a hundred and thirty times has contributed thirty extra counts; a face that shows up eighty times is short by twenty. The goodness-of-fit statistic is the sum of those shortfalls, but each shortfall is scaled by the expected count, so being short by twenty matters far more when you expected thirty than when you expected a thousand.
That scaling is the whole trick. Without it, a shortfall of ten would look equally alarming whether you expected twelve or twelve thousand, which is obviously wrong β twelve is almost certainly noise, twelve thousand is almost certainly a real effect. Dividing each squared shortfall by the expected count converts the raw difference into something measured in units of natural sampling variability, and the resulting sum behaves, under the null hypothesis, like a chi-square distribution with degrees of freedom equal to the number of categories minus one.
Here O_i is the observed count in category i, E_i the expected count, and k the number of categories. Large values mean the observed counts are far from the model in units of sampling noise, which is evidence against the model. Small values mean the counts sit where the model says they should.
Degrees of freedom and expected counts
Degrees of freedom in this test are almost always k β 1, but only when the expected counts are fully specified by the null hypothesis. If you estimated any parameter from the data β say, testing whether a Poisson distribution fits after using the sample mean as the rate β each estimated parameter costs one degree of freedom. Confusing the two is a common source of slightly-wrong p-values that survive review because they land on the same side of the threshold.
Expected counts also carry the test's most important assumption. The chi-square approximation is unreliable when expected counts are small, because the discrete distribution of the statistic is poorly approximated by the continuous chi-square curve in that region. The conventional guidance is that no expected count should fall below one, and that no more than twenty per cent of them should fall below five.
| Expected count | Typical verdict | What to do |
|---|---|---|
| All at least 5 | approximation reliable | report the test as usual |
| A few below 5, none below 1 | usually acceptable | report counts alongside the p-value |
| Many below 5 | approximation unreliable | combine sparse categories |
| Any below 1 | invalid | combine categories or collect more data |
Combining sparse categories is not a cosmetic step; it changes the hypothesis being tested. If you merge "other" with "miscellaneous", you are now testing a coarser model, and that is a legitimate choice β provided you decide the grouping before looking at which categories look inconvenient, rather than after.
Running the test in Python
The manual calculation is worth doing once so the library call is not a black box. After that, scipy.stats.chisquare is the tool you will reach for.
import numpy as np
from scipy import stats
# A die rolled 600 times: is it fair?
observed = np.array([95, 110, 102, 98, 105, 90])
n = observed.sum()
expected_uniform = np.full(6, n / 6)
# Hand calculation, category by category
differences = observed - expected_uniform
contributions = differences**2 / expected_uniform
statistic = contributions.sum()
print("Contributions by face:")
for face, (o, e, c) in enumerate(
zip(observed, expected_uniform, contributions), start=1
):
print(f" Face {face}: observed={o}, expected={e:.1f}, chi2={c:.3f}")
print(f"\nChi-square statistic: {statistic:.4f}")
print(f"Degrees of freedom: {len(observed) - 1}")
print(f"Critical value (0.05): {stats.chi2.ppf(0.95, df=5):.4f}")
# The library call, which should match
result = stats.chisquare(observed, f_exp=expected_uniform)
print(f"\nscipy statistic: {result.statistic:.4f}")
print(f"scipy p-value: {result.pvalue:.4f}")
Output of that script shows the statistic around 3.17 with a p-value near 0.67, comfortably above any conventional threshold. The die shows nothing unusual: six hundred rolls will not distribute perfectly, and the observed deviations are the size you would expect from sampling alone. Note that scipy.stats.chisquare infers degrees of freedom from the length of the input when no parameter is estimated, which is correct here but not in the next section's setting.
Testing against a non-uniform model
Uniform expected counts are the special case. The general case specifies expected proportions and multiplies them by the sample size, and this is where the test earns its keep β checking a claimed product mix, a Mendelian ratio, or a historical baseline.
# Marketing claims the product mix is 40/25/20/15
observed = np.array([118, 72, 55, 55])
proportions = np.array([0.40, 0.25, 0.20, 0.15])
expected = proportions * observed.sum()
result = stats.chisquare(observed, f_exp=expected)
print(f"Observed: {observed}")
print(f"Expected: {expected}")
print(f"Statistic: {result.statistic:.3f}, p = {result.pvalue:.4f}")
# Standardised residuals show which categories drive the result
residuals = (observed - expected) / np.sqrt(expected)
print("\nStandardised residuals:")
for cat, r in zip(["A", "B", "C", "D"], residuals):
print(f" {cat}: {r:+.2f}")
# A gene ratio of 3:1
gene_observed = np.array([780, 220])
gene_expected = np.array([750, 250])
g = stats.chisquare(gene_observed, f_exp=gene_expected)
print(f"\nMendelian 3:1 -> chi2 = {g.statistic:.3f}, p = {g.pvalue:.4f}")
# Estimating a parameter: Poisson rate from the sample mean
counts = np.array([0, 1, 2, 3, 4, 5])
obs = np.array([17, 32, 19, 8, 3, 1])
lam = np.average(counts, weights=obs) # estimate the rate
exp_poisson = stats.poisson.pmf(counts, lam) * obs.sum()
pooled = np.append(exp_poisson[:5], exp_poisson[5:].sum()) # pool the tail
chi2, p = stats.chisquare(obs[:6], f_exp=np.append(pooled[:5], pooled[5]))
# Pooling the sparse tail is what keeps the approximation valid
dof = len(obs) - 1 - 1 # one parameter estimated
print(f"Poisson fit: chi2 = {chi2:.3f}, df = {dof}, p = {p:.4f}")
The Poisson example illustrates both refinements at once: estimating the rate from the data costs a degree of freedom, and pooling the sparse upper tail keeps every expected count above five. Doing either step silently produces a test that looks rigorous and is not.
Reading the output and reporting
A p-value from this test is a statement about compatibility, not about probability of the null. A large p-value does not prove the model is correct; it says the data are not inconsistent with it, and a low-powered study will fail to reject almost anything. The honest report includes the statistic, the degrees of freedom, the p-value, the observed counts, and the expected counts, so a reader can judge for themselves whether the expected counts were large enough for the approximation to be trustworthy.
Effect size matters alongside significance. CramΓ©r's V for a one-way goodness-of-fit test is the square root of the chi-square statistic divided by the sample size, and it puts the deviation on a zero-to-one scale that is comparable across studies.
def cramers_v_gof(chi2, n):
"""Effect size for a one-way goodness-of-fit test."""
return np.sqrt(chi2 / n)
result = stats.chisquare([118, 72, 55, 55], f_exp=[100, 50, 40, 30])
v = cramers_v_gof(result.statistic, 300)
print(f"chi2 = {result.statistic:.3f}, p = {result.pvalue:.4f}, V = {v:.3f}")
# Power intuition: how large a deviation is detectable at n = 200?
from scipy.stats import chi2 as chi2_dist
def min_detectable_effect(df, n, alpha=0.05, power=0.80):
"""Rough non-centrality based threshold for a given power."""
crit = chi2_dist.ppf(1 - alpha, df)
# Expected statistic under a modest deviation
return crit, n
crit, _ = min_detectable_effect(df=3, n=200)
print(f"Critical value at df=3, alpha=0.05: {crit:.3f}")
print("Anything smaller cannot be distinguished from noise at n=200.")
Reporting the critical value alongside the p-value is a small courtesy that makes the decision rule visible, especially for readers who think in terms of rejection regions rather than continuous p-values.
When the approximation fails
Three situations break the chi-square approximation, and each has a recognised remedy. Sparse expected counts, discussed above, are fixed by pooling categories. Very large samples create the opposite problem: trivially small deviations become statistically significant, and the test rejects models that are substantively fine. And ordered categories throw away information the test cannot use β if your categories have a natural order, a trend test or an exact test is more powerful.
# Huge sample: a trivial deviation becomes "significant"
tiny_deviation = np.array([40010, 39990])
uniform = np.array([40000, 40000])
huge = stats.chisquare(tiny_deviation, f_exp=uniform)
print(f"Huge n, tiny deviation: chi2 = {huge.statistic:.4f}, p = {huge.pvalue:.4f}")
# The p-value is small, but the deviation is two hundredths of a per cent.
# Exact alternative for sparse counts
from scipy.stats import chisquare as _ # keep the import explicit
sparse_obs = np.array([8, 2, 1])
sparse_exp = np.array([4.5, 4.5, 2.0])
print("Expected counts below 5 -> pool or use a Monte Carlo test.")
# Monte Carlo p-value via simulation, valid regardless of counts
rng = np.random.default_rng(42)
n = sparse_obs.sum()
probs = sparse_exp / sparse_exp.sum()
simulated = rng.multinomial(n, probs, size=10000)
sim_stats = ((simulated - sparse_exp) ** 2 / sparse_exp).sum(axis=1)
obs_stat = ((sparse_obs - sparse_exp) ** 2 / sparse_exp).sum()
mc_p = (sim_stats >= obs_stat).mean()
print(f"Monte Carlo p-value: {mc_p:.4f}")
The Monte Carlo approach is worth remembering because it removes the expected-count restriction entirely: you simulate from the null model, compute the statistic for each simulated dataset, and ask how often the simulated statistic exceeds the observed one. It costs compute instead of assumptions, and for the sparse tables that appear in real work β rare categories, small clinical cohorts β it is the correct default rather than a fallback.
Worked example: a full investigation
Putting the pieces together with a realistic scenario makes the workflow concrete. Suppose a retailer claims its weekly sales split across five regions matches last year's profile, and the analyst must decide whether the claim survives scrutiny.
import pandas as pd
regions = ["North", "South", "East", "West", "Central"]
observed = np.array([820, 610, 590, 780, 400])
last_year = np.array([0.22, 0.18, 0.17, 0.23, 0.20])
expected = last_year * observed.sum()
table = pd.DataFrame({
"region": regions,
"observed": observed,
"expected": expected,
"residual": (observed - expected) / np.sqrt(expected),
})
print(table.round(2).to_string(index=False))
result = stats.chisquare(observed, f_exp=expected)
print(f"\nchi2({len(observed)-1}) = {result.statistic:.2f}, p = {result.pvalue:.4f}")
print(f"Cramer's V = {cramers_v_gof(result.statistic, observed.sum()):.3f}")
if result.pvalue < 0.05:
drivers = table.loc[table["residual"].abs() > 2, "region"].tolist()
print(f"Reject the claimed mix. Largest drivers: {', '.join(drivers)}")
else:
print("The claimed mix is compatible with this week's sales.")
The residual column is what turns a reject into an explanation. A significant chi-square says the mix changed; the standardised residuals say where β and a residual beyond roughly two in absolute value marks the categories carrying the evidence. Reporting that table next to the p-value is the difference between a finding a regional manager can act on and a number they cannot.
Mistakes that undermine the test
Common Mistakes
Using the test when expected counts fall below five
Fix: Pool sparse categories before computing the statistic, or switch to a Monte Carlo p-value.
Forgetting that estimated parameters cost degrees of freedom
Fix: Subtract one degree of freedom per parameter estimated from the sample, not just for the categories.
Treating a large p-value as proof the model is correct
Fix: Report it as compatibility with the data, and note the sample size that determined power.
Choosing category groupings after seeing the results
Fix: Fix the grouping from domain knowledge before computing anything, or the test is circular.
Reporting only the p-value
Fix: Include observed counts, expected counts, and residuals so readers can judge magnitude.
Applying the test to ordered categories as if they were nominal
Fix: Use a trend test or exact test when the order carries information the chi-square discards.
Ignoring very large samples that make trivial deviations significant
Fix: Pair the p-value with an effect size and judge whether the deviation is worth acting on.
Practices that keep the analysis defensible
Best Practices
- Compute expected counts and inspect them before running the test.
- Show the contribution of each category so the statistic is auditable.
- Use standardised residuals to explain a significant result, not just to declare one.
- Report CramΓ©r's V alongside the p-value to convey magnitude.
- Pool sparse categories on domain grounds, documented before the analysis.
- Prefer Monte Carlo p-values when any expected count is small.
- State the null distribution explicitly, including any estimated parameters.
- Check sample size: at large n, significance is cheap and effect size is the real news.
Key takeaways
Key Takeaways
- The test asks whether counted categories match a distribution specified in advance.
- Each shortfall is divided by its expected count, so deviations are measured in units of sampling noise.
- Degrees of freedom are k β 1, reduced further for any parameter estimated from the data.
- Expected counts below five break the approximation; pool categories or simulate the null.
- Standardised residuals identify which categories drive a significant result.
- Effect size such as CramΓ©r's V carries the magnitude the p-value cannot.
- At very large samples the test rejects trivial deviations, so practical significance must be judged separately.
Where to go next
- Chi-Square Test of Independence β the two-variable sibling of this test.
- One-Way ANOVA β comparing means across groups when the outcome is continuous.
- Permutation Tests β an exact alternative when distributional approximations are shaky.
- Frequency Distributions β the counting foundation this test is built on.