Skip to content

EProportions & counts · proportion.symmetry

Symmetry and marginal homogeneity (Stuart–Maxwell, Bhapkar, Bowker)

Did the distribution of a categorical rating change between two paired measurements?

For a categorical variable measured twice on the same subjects (two raters, before/after, left and right eye), tests whether the two margins are the same (Stuart–Maxwell and Bhapkar marginal homogeneity) and whether the square table is symmetric (Bowker's generalization of McNemar's test), with the marginal distributions and their differences.

Verified in Python and R Python and R agree to 10 decimals

A real result

Example “Vision”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Symmetry and marginal homogeneityRecorded · Python and R agreeRecorded 2026-11-17 · 27 values compared
R

Stuart–Maxwell χ²(3, N = 7477) = 11.96, p = .008

Stuart–Maxwell χ²
11.957
p (Stuart–Maxwell)
.008
Bhapkar χ²
11.976
p (Bhapkar)
.007
Bowker χ² (6 df)
19.107
p (Bowker)
.004

Plots

Marginal distributionsHow do category counts compare across subgroups?
View data
measurementsharecategory
right eye0.26431 highest
right eye0.30172
right eye0.32853
right eye0.10554 lowest
left eye0.25501 highest
left eye0.29722
left eye0.33533
left eye0.11254 lowest
Paired classificationsWhat do the values of a square or rectangular result matrix look like at a glance?
View data
left eyeright eyecount
1 highest1 highest1,520
21 highest266
31 highest124
4 lowest1 highest66
1 highest2234
221,512
32432
4 lowest278
1 highest3117
23362
331,772
4 lowest3205
1 highest4 lowest36
24 lowest82
34 lowest179
4 lowest4 lowest492

Assumptions

  • Paired observations — Each row holds both classifications of one subject.
  • Enough off-diagonal counts — 2181 subjects changed category (3 degrees of freedom); with few changes the χ² approximation is rough.

Marginal distributions

Categoryright eyeleft eyeDifference
1 highest0.26430.25500.0092
20.30170.29720.0045
30.32850.3353−0.0068
4 lowest0.10550.1125−0.0070

right eye (rows) × left eye (columns)

right eye1 highest234 lowest
1 highest1,52026612466
22341,51243278
31173621,772205
4 lowest3682179492
  • Marginal homogeneity: the share of each category is the same on both occasions. Symmetry (Bowker) is stronger: every change i → j is as common as j → i.
Python

Stuart–Maxwell χ²(3, N = 7477) = 11.96, p = .008

Stuart–Maxwell χ²
11.957
p (Stuart–Maxwell)
.008
Bhapkar χ²
11.976
p (Bhapkar)
.007
Bowker χ² (6 df)
19.107
p (Bowker)
.004

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Paired observations — Each row holds both classifications of one subject.
  • Enough off-diagonal counts — 2181 subjects changed category (3 degrees of freedom); with few changes the χ² approximation is rough.

Marginal distributions

Categoryright eyeleft eyeDifference
1 highest0.26430.25500.0092
20.30170.29720.0045
30.32850.3353−0.0068
4 lowest0.10550.1125−0.0070

right eye (rows) × left eye (columns)

right eye1 highest234 lowest
1 highest1,52026612466
22341,51243278
31173621,772205
4 lowest3682179492
  • Marginal homogeneity: the share of each category is the same on both occasions. Symmetry (Bowker) is stronger: every change i → j is as common as j → i.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Visions4_vision · first: right eye · second: left eye
  • Vision bowkers4_vision · first: right eye · second: left eye
  • Coffee bhapkars4_coffee · first: first purchase · second: second purchase
  • Drugs 2x2s4_drugs · first: drug A · second: drug C
  • Degenerate n2s4_vision · first: right eye · second: left eye

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Paired proportions: McNemar · Statistics Guide · E — Compare proportions / frequencies
  • Stratified, repeated, multiway, survey · Statistics Guide · E — Compare proportions / frequencies
  • Categorical (2 raters): Cohen's κ · Statistics Guide · G — Agreement / reliability

What you need

First measurementcategorical / boolean · 1 column · 2–20 levels
The first categorical measurement on each subject.
Second measurementcategorical / boolean · 1 column · 2–20 levels
The second measurement on the same subjects, with the same categories.

Choices you make

hypothesis

Main testdefault stuart_maxwell

Stuart–Maxwell and Bhapkar test whether the row and column margins match; Bowker tests symmetry of the whole table.

  • Stuart–Maxwell (marginal homogeneity)(default) — Tests whether row and column shares match; the usual choice for marginal homogeneity.
  • Bhapkar (marginal homogeneity, more powerful in large samples) — Tests the same question with the Wald form; a little more powerful in large samples.
  • Bowker (symmetry of the whole table) — Tests whether the whole table mirrors itself across the diagonal; stricter than marginal homogeneity.
Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Paired observations

    Both columns describe the same subject on each row, with the same categories.

  • Enough off-diagonal counts

    The χ² approximations need reasonably many subjects who change category.

What it reports

  • Tests: Marginal homogeneity / symmetry
n
How many independent units the analysis used; it sets precision and power.
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
stat
A single number that summarizes how far your data are from what H₀ predicts.
df
How much independent information is left to estimate variability after fitting the model.
p
How surprising your data would be if the null hypothesis were true, as a probability.
test_label
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
bowker
The Wilcoxon signed-rank test assumes paired differences are symmetric around their center.
bowker_df
How much independent information is left to estimate variability after fitting the model.
bowker_p
How surprising your data would be if the null hypothesis were true, as a probability.
sm
The Wilcoxon signed-rank test assumes paired differences are symmetric around their center.
sm_p
How surprising your data would be if the null hypothesis were true, as a probability.
bhapkar
The Wilcoxon signed-rank test assumes paired differences are symmetric around their center.
bhapkar_p
How surprising your data would be if the null hypothesis were true, as a probability.
agreement
Observed agreement is the share of ratings that match; chance agreement is the share expected to match anyway.
n_changed
How many independent units the analysis used; it sets precision and power.

Per group, level or term: marg_first[<level>], marg_second[<level>], marg_diff[<level>]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Bowker's statistic leaves out pairs of cells that are both empty (and their degree of freedom); R's mcnemar.test returns NaN for such tables, so R uses mcnemar.test only when no pair is empty and the twin otherwise. Stuart–Maxwell and Bhapkar are closed forms (twins of DescTools::StuartMaxwellTest / BhapkarTest).
Python

The exact script CodeSplash ran for example “Vision” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Symmetry and marginal homogeneity (Stuart–Maxwell, Bhapkar, Bowker)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.symmetry 1.0.1 · spec cc930f241a7010d7
# Dataset: s4_vision (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import categorical_adv as cat  # Bowker, Stuart–Maxwell, Bhapkar (twins of codesplashr::cs_cat_*)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s4_vision.parquet", columns=["right eye", "left eye"])
n_input = len(df)
df["right eye"] = pd.Categorical(df["right eye"], categories=["1 highest", "2", "3", "4 lowest"])  # stored level order
df["left eye"] = pd.Categorical(df["left eye"], categories=["1 highest", "2", "3", "4 lowest"])  # stored level order
df = df.dropna(subset=["right eye", "left eye"])  # listwise deletion over the analysis columns
df["right eye"] = df["right eye"].cat.remove_unused_categories()
df["left eye"] = df["left eye"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["right eye", "left eye"])  # infinite values stop the run (registry/errors.yaml)

# %% Square table (same categories on both axes, first column's stored order)
f1, f2 = "right eye", "left eye"
lv1 = [str(v) for v in df[f1].cat.categories]
lv2 = [str(v) for v in df[f2].cat.categories]
levels = lv1 + [v for v in lv2 if v not in lv1]
a = pd.Categorical(df[f1].astype(str), categories=levels)
b = pd.Categorical(df[f2].astype(str), categories=levels)
tab = pd.crosstab(a, b, dropna=False).reindex(index=levels, columns=levels, fill_value=0).to_numpy(dtype=float)
n, k = int(tab.sum()), len(levels)
if k < 2:
    cs.cs_error("CS_E_UNDEFINED", what="The symmetry test", reason="the measurements need at least two categories")

# %% Tests
# statsmodels' SquareTable(tab).symmetry() / .homogeneity("stuart_maxwell" | "bhapkar") are the
# library equivalents; the twins also handle pairs of empty cells (Bowker) explicitly.
bw = cat.bowker(tab)
mh = cat.stuart_maxwell(tab)
test = "stuart_maxwell"
labels = {"stuart_maxwell": "Stuart–Maxwell", "bhapkar": "Bhapkar", "bowker": "Bowker"}
stat, dof, p = {
    "stuart_maxwell": (mh["sm"], mh["df"], mh["sm_p"]),
    "bhapkar": (mh["bhapkar"], mh["df"], mh["bhapkar_p"]),
    "bowker": (bw["stat"], bw["df"], bw["p"]),
}[test]
agreement = float(np.trace(tab)) / n
changed = n - int(np.trace(tab))
m1, m2 = tab.sum(axis=1) / n, tab.sum(axis=0) / n

# %% Assumptions
assumptions = [
    {"key": "pairing", "label": "Paired observations", "status": "info", "detail": "Each row holds both classifications of one subject."},
    {"key": "sample_size", "label": "Enough off-diagonal counts", "status": "pass" if changed >= 10 * max(dof, 1) else "warn",
     "detail": f"{changed} subjects changed category ({dof} degrees of freedom); with few changes the χ² approximation is rough."},
]

# %% Result
values = {
    "n": n, "k": k, "stat": stat, "df": dof, "p": p, "test_label": labels[test],
    "bowker": bw["stat"], "bowker_df": bw["df"], "bowker_p": bw["p"],
    "sm": mh["sm"], "sm_p": mh["sm_p"], "bhapkar": mh["bhapkar"], "bhapkar_p": mh["bhapkar_p"],
    "agreement": agreement, "n_changed": changed,
}
for lv, x1, x2 in zip(levels, m1, m2):
    values[f"marg_first[{lv}]"] = float(x1)
    values[f"marg_second[{lv}]"] = float(x2)
    values[f"marg_diff[{lv}]"] = float(x1 - x2)
cells = [(levels[i], levels[j], tab[i, j]) for i in range(k) for j in range(k)]
cs.publish({
    "method": "proportion.symmetry",
    "methodVersion": "1.0.1",
    "title": "Symmetry and marginal homogeneity",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": f"{n} subjects classified twice into {k} categories ({agreement:.1%} unchanged); {labels[test]} χ²({dof}) = {stat:.2f}, {cs.fmt_p(p)}.",
    "apa": f"{labels[test]} χ²({dof}, N = {n}) = {stat:.2f}, {cs.fmt_p(p)}",
    "statistics": [
        {"key": "sm", "label": "Stuart–Maxwell χ²", "value": mh["sm"]},
        {"key": "sm_p", "label": "p (Stuart–Maxwell)", "value": mh["sm_p"], "format": "p"},
        {"key": "bhapkar", "label": "Bhapkar χ²", "value": mh["bhapkar"]},
        {"key": "bhapkar_p", "label": "p (Bhapkar)", "value": mh["bhapkar_p"], "format": "p"},
        {"key": "bowker", "label": f"Bowker χ² ({bw['df']} df)", "value": bw["stat"]},
        {"key": "bowker_p", "label": "p (Bowker)", "value": bw["p"], "format": "p"},
    ],
    "tables": [
        {"key": "margins", "title": "Marginal distributions",
         "columns": [{"key": "level", "label": "Category", "type": "string"},
                     {"key": "first", "label": f1, "type": "number", "format": "percent"},
                     {"key": "second", "label": f2, "type": "number", "format": "percent"},
                     {"key": "diff", "label": "Difference", "type": "number", "format": "percent"}],
         "rows": [{"level": lv, "first": float(x1), "second": float(x2), "diff": float(x1 - x2)} for lv, x1, x2 in zip(levels, m1, m2)]},
        {"key": "table", "title": f"{f1} (rows) × {f2} (columns)",
         "columns": [{"key": "row", "label": f1, "type": "string"}] + [{"key": f"c{j}", "label": lv, "type": "integer"} for j, lv in enumerate(levels)],
         "rows": [{"row": lv, **{f"c{j}": int(tab[i, j]) for j in range(k)}} for i, lv in enumerate(levels)]},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": ["Marginal homogeneity: the share of each category is the same on both occasions. Symmetry (Bowker) is stronger: every change i → j is as common as j → i."],
    "charts": [
        cs.chart("margins", "bar-grouped", "Marginal distributions",
                 {"x": cs.col("category", levels + levels), "group": cs.col("measurement", [f1] * k + [f2] * k),
                  "value": cs.col("share", [float(v) for v in m1] + [float(v) for v in m2])}),
        cs.chart("table", "matrix-heatmap", "Paired classifications",
                 {"row": cs.col(f1, [c[0] for c in cells]), "col": cs.col(f2, [c[1] for c in cells]),
                  "value": cs.col("count", [float(c[2]) for c in cells])}),
    ],
    "values": values,
})
R

The exact script CodeSplash ran for example “Vision” · R version 4.5.1 (2025-06-13)

# Symmetry and marginal homogeneity (Stuart–Maxwell, Bhapkar, Bowker)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.symmetry 1.0.1 · spec cc930f241a7010d7
# Dataset: s4_vision (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_cat_bowker, cs_cat_stuart_maxwell (twins of DescTools::StuartMaxwellTest / BhapkarTest)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s4_vision.parquet", col_select = c("right eye", "left eye")))
n_input <- nrow(df)
df[["right eye"]] <- factor(df[["right eye"]], levels = c("1 highest", "2", "3", "4 lowest"))  # stored level order
df[["left eye"]] <- factor(df[["left eye"]], levels = c("1 highest", "2", "3", "4 lowest"))  # stored level order
df <- df[stats::complete.cases(df[c("right eye", "left eye")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("right eye", "left eye"))  # infinite values stop the run (registry/errors.yaml)

# %% Square table (same categories on both axes, first column's stored order)
f1 <- "right eye"
f2 <- "left eye"
lv1 <- levels(df[[f1]])
lv2 <- levels(df[[f2]])
lvls <- c(lv1, setdiff(lv2, lv1))
tab <- table(factor(as.character(df[[f1]]), levels = lvls), factor(as.character(df[[f2]]), levels = lvls))
n <- sum(tab)
k <- length(lvls)
if (k < 2) cs_error("CS_E_UNDEFINED", what = "The symmetry test", reason = "the measurements need at least two categories")

# %% Tests
# Bowker = mcnemar.test(tab) when no pair of cells is empty (mcnemar.test returns NaN otherwise).
off <- tab + t(tab)
bw <- if (all(off[upper.tri(off)] > 0)) {
  mt <- stats::mcnemar.test(tab, correct = FALSE)
  list(stat = unname(mt$statistic), df = unname(mt$parameter), p = mt$p.value)
} else {
  cs_cat_bowker(tab)
}
mh <- cs_cat_stuart_maxwell(tab)
test <- "stuart_maxwell"
labels <- c(stuart_maxwell = "Stuart–Maxwell", bhapkar = "Bhapkar", bowker = "Bowker")
res <- switch(test,
  stuart_maxwell = list(stat = mh$sm, df = mh$df, p = mh$sm_p),
  bhapkar = list(stat = mh$bhapkar, df = mh$df, p = mh$bhapkar_p),
  bowker = list(stat = bw$stat, df = bw$df, p = bw$p)
)
stat <- res$stat
dof <- res$df
p <- res$p
agreement <- sum(diag(tab)) / n
changed <- n - sum(diag(tab))
m1 <- as.numeric(rowSums(tab)) / n
m2 <- as.numeric(colSums(tab)) / n

# %% Assumptions
assumptions <- list(
  list(key = "pairing", label = "Paired observations", status = "info", detail = "Each row holds both classifications of one subject."),
  list(key = "sample_size", label = "Enough off-diagonal counts", status = if (changed >= 10 * max(dof, 1)) "pass" else "warn",
       detail = sprintf("%d subjects changed category (%d degrees of freedom); with few changes the χ² approximation is rough.", changed, as.integer(dof)))
)

# %% Result
values <- list(
  n = n, k = k, stat = stat, df = dof, p = p, test_label = labels[[test]],
  bowker = bw$stat, bowker_df = bw$df, bowker_p = bw$p,
  sm = mh$sm, sm_p = mh$sm_p, bhapkar = mh$bhapkar, bhapkar_p = mh$bhapkar_p,
  agreement = agreement, n_changed = changed
)
for (i in seq_len(k)) {
  values[[sprintf("marg_first[%s]", lvls[i])]] <- m1[i]
  values[[sprintf("marg_second[%s]", lvls[i])]] <- m2[i]
  values[[sprintf("marg_diff[%s]", lvls[i])]] <- m1[i] - m2[i]
}
cell_rows <- rep(lvls, each = k)
cell_cols <- rep(lvls, times = k)
cell_vals <- as.numeric(t(unclass(tab)))
table_rows <- lapply(seq_len(k), function(i) {
  r <- list(row = lvls[i])
  for (j in seq_len(k)) r[[sprintf("c%d", j - 1)]] <- as.integer(tab[i, j])
  r
})
cs_publish(list(
  method = "proportion.symmetry",
  methodVersion = "1.0.1",
  title = "Symmetry and marginal homogeneity",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = sprintf("%d subjects classified twice into %d categories (%.1f%% unchanged); %s χ²(%d) = %.2f, %s.",
                    as.integer(n), k, 100 * agreement, labels[[test]], as.integer(dof), stat, cs_fmt_p(p)),
  apa = sprintf("%s χ²(%d, N = %d) = %.2f, %s", labels[[test]], as.integer(dof), as.integer(n), stat, cs_fmt_p(p)),
  statistics = list(
    list(key = "sm", label = "Stuart–Maxwell χ²", value = mh$sm),
    list(key = "sm_p", label = "p (Stuart–Maxwell)", value = mh$sm_p, format = "p"),
    list(key = "bhapkar", label = "Bhapkar χ²", value = mh$bhapkar),
    list(key = "bhapkar_p", label = "p (Bhapkar)", value = mh$bhapkar_p, format = "p"),
    list(key = "bowker", label = sprintf("Bowker χ² (%d df)", as.integer(bw$df)), value = bw$stat),
    list(key = "bowker_p", label = "p (Bowker)", value = bw$p, format = "p")
  ),
  tables = list(
    list(key = "margins", title = "Marginal distributions",
         columns = list(list(key = "level", label = "Category", type = "string"),
                        list(key = "first", label = f1, type = "number", format = "percent"),
                        list(key = "second", label = f2, type = "number", format = "percent"),
                        list(key = "diff", label = "Difference", type = "number", format = "percent")),
         rows = lapply(seq_len(k), function(i) list(level = lvls[i], first = m1[i], second = m2[i], diff = m1[i] - m2[i]))),
    list(key = "table", title = sprintf("%s (rows) × %s (columns)", f1, f2),
         columns = c(list(list(key = "row", label = f1, type = "string")),
                     lapply(seq_len(k), function(j) list(key = sprintf("c%d", j - 1), label = lvls[j], type = "integer"))),
         rows = table_rows)
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = list("Marginal homogeneity: the share of each category is the same on both occasions. Symmetry (Bowker) is stronger: every change i → j is as common as j → i."),
  charts = list(
    cs_chart("margins", "bar-grouped", "Marginal distributions",
             list(x = cs_col("category", c(lvls, lvls)), group = cs_col("measurement", c(rep(f1, k), rep(f2, k))),
                  value = cs_col("share", c(m1, m2)))),
    cs_chart("table", "matrix-heatmap", "Paired classifications",
             list(row = cs_col(f1, cell_rows), col = cs_col(f2, cell_cols), value = cs_col("count", cell_vals)))
  ),
  values = values
))

Sources

  • Bowker, A. H. (1948). A test for symmetry in contingency tables. JASA, 43, 572–574.
  • Stuart, A. (1955). A test for homogeneity of the marginal distributions in a two-way classification. Biometrika, 42, 412–416.
  • Maxwell, A. E. (1970). Comparing the classification of subjects by two independent judges. British Journal of Psychiatry, 116, 651–655.
  • Bhapkar, V. P. (1966). A note on the equivalence of two test criteria for hypotheses in categorical data. JASA, 61, 228–235.

From the CodeSplash method registry · proportion.symmetry v1.0.1.