Chi-Square Test
The tests so far dealt with means and single proportions. The chi-square (χ²) tests handle categorical data with several categories. They compare observed counts with the counts you would expect if a hypothesis were true.
There are two main versions:
| Test | Question | Example |
|---|---|---|
| Goodness of fit | Does one categorical variable follow a claimed distribution? | Are a die's faces equally likely? |
| Test of independence | Are two categorical variables related? | Does preferred snack depend on age group? |
The statistic
χ² = Σ (observed − expected)² / expectedEach category contributes its squared deviation, scaled by its expected count. If the hypothesis is true, the observed counts are close to the expected ones and χ² is small. Large values are evidence against H₀. Under H₀, the statistic approximately follows a chi-square distribution with a certain number of degrees of freedom; the p-value is the area to the right of the observed value.
Condition: all expected counts should be at least 5 (a common rule of thumb). The observations must be independent, and the data must be counts, not percentages or means.
Goodness of fit
A seed company claims its flower mix contains red, yellow, white and purple flowers in the ratio 40 : 30 : 20 : 10. A gardener grows 300 plants and counts the colours:
import numpy as np
from scipy import stats
observed = np.array([105, 98, 66, 31]) # red, yellow, white, purple
claimed = np.array([0.40, 0.30, 0.20, 0.10])
expected = observed.sum() * claimed
contributions = (observed - expected) ** 2 / expected
print("expected:", expected)
print("contributions:", contributions.round(3))
chi2 = contributions.sum()
df = len(observed) - 1
print(f"chi2 = {chi2:.3f}, df = {df}, p-value = {stats.chi2.sf(chi2, df):.4f}")
res = stats.chisquare(observed, f_exp=expected)
print(f"SciPy: chi2 = {res.statistic:.3f}, p-value = {res.pvalue:.4f}")expected: [120. 90. 60. 30.]
contributions: [1.875 0.711 0.6 0.033]
chi2 = 3.219, df = 3, p-value = 0.3590
SciPy: chi2 = 3.219, p-value = 0.3590
For goodness of fit, df = number of categories − 1. The red flowers are noticeably fewer than claimed (105 instead of 120), but overall p ≈ 0.36 > 0.05, so we fail to reject H₀: the counts are compatible with the advertised mix.
Test of independence
A cinema asked 400 visitors in three age groups which snack they bought:
import pandas as pd
from scipy import stats
table = pd.DataFrame(
{"popcorn": [72, 60, 38], "nachos": [40, 35, 15], "none": [28, 45, 67]},
index=["under 25", "25-50", "over 50"],
)
print(table)
print()
res = stats.chi2_contingency(table)
print(f"chi2 = {res.statistic:.3f}, df = {res.dof}, p-value = {res.pvalue:.2e}")
print()
print("expected counts if snack and age were independent:")
print(pd.DataFrame(res.expected_freq, index=table.index, columns=table.columns).round(1)) popcorn nachos none
under 25 72 40 28
25-50 60 35 45
over 50 38 15 67
chi2 = 38.167, df = 4, p-value = 1.03e-07
expected counts if snack and age were independent:
popcorn nachos none
under 25 59.5 31.5 49.0
25-50 59.5 31.5 49.0
over 50 51.0 27.0 42.0
The expected count for each cell is row total × column total / grand total, and df = (rows − 1) × (columns − 1) = 4. The p-value is tiny, so we reject independence: snack choice depends on age group. Comparing observed with expected counts shows how: older visitors much more often buy nothing.
Effect size: Cramér's V
A significant χ² doesn't say how strong the association is. Cramér's V scales χ² to a value between 0 (no association) and 1 (perfect association):
V = √( χ² / (n × (min(rows, columns) − 1)) )import numpy as np
from scipy import stats
table = np.array([[72, 40, 28], [60, 35, 45], [38, 15, 67]])
chi2 = stats.chi2_contingency(table).statistic
n = table.sum()
v = np.sqrt(chi2 / (n * (min(table.shape) - 1)))
print(f"Cramér's V = {v:.3f}")
print(f"SciPy: {stats.contingency.association(table, method='cramer'):.3f}")Cramér's V = 0.218
SciPy: 0.218
Common rules of thumb call V ≈ 0.1 weak, 0.3 moderate and 0.5 strong (for tables with three rows or columns the thresholds are a little lower). V ≈ 0.22 is a modest but clearly real association: age matters, but it is far from deciding snack choice on its own.
The chi-square distribution
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
x = np.linspace(0, 20, 400)
fig, ax = plt.subplots(figsize=(6, 3.2))
for df, color in [(1, "#2a78d6"), (3, "#eb6834"), (6, "#1baf7a")]:
ax.plot(x, stats.chi2.pdf(x, df), color=color, linewidth=2, label=f"df = {df}")
ax.set_ylim(0, 0.5)
ax.legend(frameon=False)
plt.tight_layout()
plt.show()
for df in [1, 3, 4, 6]:
print(f"df={df}: 5% critical value = {stats.chi2.ppf(0.95, df):.3f}")df=1: 5% critical value = 3.841
df=3: 5% critical value = 7.815
df=4: 5% critical value = 9.488
df=6: 5% critical value = 12.592
The distribution is right-skewed and only takes positive values; its mean equals its degrees of freedom. The chi-square test is always right-tailed: only large deviations count as evidence.
Note: For a 2×2 table,
chi2_contingencyapplies Yates' continuity correction by default (correction=True). For small expected counts, use Fisher's exact test (stats.fisher_exact) instead.
Test yourself
A goodness-of-fit test has 6 categories. How many degrees of freedom does it have?
- 6
- 5
- 4
- 36
In a 3×4 contingency table, how many degrees of freedom does the independence test have?
- 12
- 11
- 6
- 7
A cell's row total is 50, its column total is 80 and the grand total is 200. What is its expected count?
- 20
- 25
- 40
- 65