Categorical data needs a different tool
A large share of the questions asked of real data are about categories rather than quantities: does a patient respond or not, is an email spam, which plan did a customer choose, did a click happen. Means and t-tests have nothing to say about these outcomes, because averaging categories is meaningless. Chi-square tests are built for exactly this material. They work with counts, compare observed counts against counts that a claim predicts, and return a single statistic whose reference distribution is known in closed form.
There are two questions and, reassuringly, two tests that share one statistic. The goodness-of-fit test asks whether one categorical variable follows a specified distribution — is a six-sided fair, does the mix of support tickets match last quarter's mix. The test of independence asks whether two categorical variables are associated in a sampled population — is gender related to voting preference, does subscription plan relate to churn. Both standardise the gap between observed and expected counts and add the standardised gaps up, and both are asymptotically chi-square distributed under the null.
Goodness of fit: one variable against a claim
The procedure starts by converting the claim into expected counts. If a die is fair and rolled one hundred twenty times, each face is expected twenty times. Compute the chi-square statistic as the sum, over all categories, of the observed count minus the expected count, squared, divided by the expected count. The division is what makes the statistic comparable across categories: a gap of five counts means something different in a category expecting twenty than in one expecting two.
The degrees of freedom are the number of categories minus one when the claim fully specifies the probabilities, minus one additional parameter for every probability estimated from the data itself. That last rule is easy to forget: testing whether counts fit a normal distribution whose mean and standard deviation were estimated from the same data costs two extra degrees of freedom. A statistic above the critical value means the observed counts are implausible under the claim; it does not identify which category is responsible, so a follow-up look at standardised residuals is the natural next step.
| Test | Null hypothesis | Degrees of freedom | Typical use |
|---|---|---|---|
| Goodness of fit, fixed probabilities | Categories follow the stated distribution | k minus one | Fairness checks, mix comparisons |
| Goodness of fit, estimated parameters | Categories follow a fitted distribution | k minus one minus number of fitted parameters | Distributional fit |
| Independence, r by c table | The two variables are unrelated | r minus one times c minus one | Association in a contingency table |
Independence: two variables in one table
The test of independence starts from a contingency table of observed counts and derives the counts you would expect if the two variables were unrelated. The expected count for a cell is its row total times its column total divided by the grand total — the arithmetic of independent events written in counts. If preference and gender were independent, the proportion choosing each party would be identical across every gender, and the expected table would reproduce those proportions exactly.
The statistic then sums the standardised squared gaps across every cell of the table. Because the row and column totals are themselves computed from the data, the table loses one degree of freedom per row and per column beyond the first, giving the product of r minus one and c minus one. A large statistic means the observed allocation departs from what independence predicts. Standardised residuals — the signed square roots of each cell's contribution — show which cells are doing the work, and that follow-up is what turns a significant result into an actionable finding.
Expected frequencies and the rules that protect them
The chi-square approximation is a large-sample result, and it degrades when counts get small. The standard guidance is that no expected count should fall below one and no more than twenty percent of cells should have expected counts under five. When those conditions fail, the reference distribution no longer matches the statistic and the p-value is unreliable, usually too small, which means you would declare significance too often.
For two-by-two tables the remedy is Fisher's exact test, which computes the probability of the observed table and all tables more extreme under fixed margins, giving an exact p-value with no approximation at all. For larger tables, collapse sparse categories when the collapse is substantively meaningful, collect more data, or use a Monte Carlo chi-square that estimates the reference distribution by resampling. Every one of these choices should be recorded in the analysis, because moving categories around after seeing the result is a form of p-hacking.
Effect size and what the p-value leaves out
With a large enough sample, every chi-square test becomes significant — trivial departures from independence produce large statistics when n is huge. Effect size answers the question the p-value cannot: how strong is the association. Cramér's V divides the chi-square statistic by n and by the smaller table dimension minus one, then takes the square root, landing on a number between zero and one. Benchmarks depend on the table size; for a two-by-two table roughly zero point one is small, zero point three medium, and zero point five large, while larger tables need correspondingly smaller thresholds.
Chi-square also has a blind spot: it ignores ordering. If the categories are ordinal — a five-point satisfaction scale — the test treats the gap between adjacent ratings the same as the gap between extremes, throwing away information. Trend tests such as the Cochran-Armitage test restore that ordering and gain power. And chi-square detects association without direction or magnitude in the original units; to model the same relationship with continuous predictors or to quantify it in interpretable terms, follow up with logistic regression.
Contingency tables in Python
import numpy as np
from scipy import stats
def goodness_of_fit(observed, expected=None, label=None):
observed = np.asarray(observed, dtype=float)
if expected is None:
expected = observed.mean()
expected = np.full_like(observed, expected, dtype=float)
chi2 = np.sum((observed - expected) ** 2 / expected)
df = observed.size - 1
p = 1 - stats.chi2.cdf(chi2, df)
residuals = (observed - expected) / np.sqrt(expected)
return chi2, df, p, residuals
counts = np.array([18, 15, 22, 17, 20, 28]) # six faces, 120 rolls
chi2, df, p, resid = goodness_of_fit(counts)
print(f"chi2={chi2:.3f} df={df} p={p:.4f}")
print("standardised residuals:", np.round(resid, 2))
print("critical value at 0.05:", stats.chi2.ppf(0.95, df))
The statistic lands well below the critical value, so the die shows no detectable bias, and the residuals confirm no single face is pulling the result. Reading residuals rather than only the p-value is what tells you where a real departure would show up.
The independence test and its effect size come next.
import numpy as np
from scipy import stats
def cramers_v(chi2, n, table_shape):
r, c = table_shape
return np.sqrt(chi2 / (n * (min(r, c) - 1)))
def check_assumptions(table):
expected = np.outer(table.sum(axis=1), table.sum(axis=0)) / table.sum()
return expected.min(), (expected < 5).mean()
table = np.array([
[52, 38, 30],
[28, 55, 47],
[20, 27, 43],
])
chi2, p, dof, expected = stats.chi2_contingency(table)
n = table.sum()
v = cramers_v(chi2, n, table.shape)
min_exp, frac_small = check_assumptions(table)
print(f"chi2={chi2:.2f} df={dof} p={p:.4f} Cramer's V={v:.3f}")
print(f"smallest expected={min_exp:.2f} cells below 5: {frac_small:.0%}")
observed_minus = (table - expected) / np.sqrt(expected)
print("standardised residuals:\n", np.round(observed_minus, 2))
if min_exp < 5:
oddsr, pfisher = stats.fisher_exact(table[:2, :2])
print("Fisher exact on the 2x2 sub-table:", round(pfisher, 4))
The output shows both the association test and the diagnostic that validates it. When any expected count dips under five, the Fisher branch is the correct fallback for a two-by-two slice, and the residuals pinpoint the cell that drives the significance.
Chi-square pitfalls
Common Mistakes
Running chi-square when more than twenty percent of expected counts are below five
Fix: Collapse categories, gather more data, or switch to Fisher's exact test for small tables.
Reading a significant chi-square as showing which cell differs
Fix: Inspect standardised residuals or run a pre-planned post-hoc comparison with its own correction.
Quoting only the p-value on a large sample
Fix: Report Cramér's V; with big n everything is significant and only effect size tells you if it matters.
Applying the test to ordinal categories as if order did not matter
Fix: Use a trend test such as Cochran-Armitage, or model the ordering explicitly.
Estimating parameters from the data without reducing degrees of freedom
Fix: Subtract one degree of freedom for each parameter fitted from the same counts.
Treating counts from repeated measures as independent
Fix: Chi-square assumes independent observations; use a test for paired categorical data instead.
Chi-square in one page
Where to go next
- Chi-Square Distribution derives the reference distribution and its critical values.
- Chi-Square Goodness of Fit works through full distributional checks.
- Chi-Square Test of Independence covers residuals and post-hoc analysis.
- Logistic Regression models the same associations with continuous predictors.