Correspondence analysis: a map of a two-way table
Correspondence analysis turns a table of counts into a map where similar rows sit together and similar columns sit together. Learn to read inertia, contributions and cos², and the one distance a symmetric map can't show.
What runs in CodeSplash
- Correspondence analysis (CA) Verified in Python and R
You will be able to
- Explain inertia as the table's departure from independence (χ²/n)
- Read a symmetric map within rows and within columns
- Use contributions and cos² before naming a dimension
- Choose a biplot map to read rows against columns
From a χ² test to a map
ReadA χ² test says whether two categorical variables are related. It doesn't say how: which rows lean toward which columns.
Correspondence analysisCorrespondence analysisMaps the rows and columns of a two-way table so similar profiles sit close; its dimensions split the χ² association. answers that. It compares each row's profile (its counts as shares) with the average profile, and draws rows with similar profiles close together. Columns get the same treatment.
Run it
In the appCorrespondence analysis, total inertia = 0.085, χ²(12) = 16.44, p = .172
- Total inertia
- 0.0852
- χ²
- 16.442
- p
- .172
- Shown by 2 dimensions
- 99.5%
Plots
View data
| Level | Mass | Set | Dimension 1 (87.8%) | Dimension 2 (11.8%) |
|---|---|---|---|---|
| Senior managers | 0.0570 | staff | 0.0658 | 0.1937 |
| Junior managers | 0.0933 | staff | −0.2590 | 0.2433 |
| Senior employees | 0.2642 | staff | 0.3806 | 0.0107 |
| Junior employees | 0.4560 | staff | −0.2330 | −0.0577 |
| Secretaries | 0.1295 | staff | 0.2011 | −0.0789 |
| Non-smoker | 0.3161 | smoking | 0.3933 | 0.0305 |
| Light | 0.2332 | smoking | −0.0995 | −0.1411 |
| Medium | 0.3212 | smoking | −0.1963 | −0.0074 |
| Heavy | 0.1295 | smoking | −0.2938 | 0.1978 |
View data
| Dimension | Cumulative share | Share of inertia |
|---|---|---|
| 1 | 0.8776 | 0.8776 |
| 2 | 0.9951 | 0.1176 |
| 3 | 1 | 0.0049 |
Assumptions
- Expected counts (for the χ² p-value) — 35% of cells expect fewer than 5 (smallest 1.4). The χ² p-value is approximate; the map itself does not depend on it, but rare levels can dominate a dimension — check their contributions.
- Counts of independent units — CA describes the table; the χ² test treats every count as an independent unit.
Principal inertias
| Dimension | Principal inertia | Share | Cumulative |
|---|---|---|---|
| 1 | 0.0748 | 87.8% | 87.8% |
| 2 | 0.0100 | 11.8% | 99.5% |
| 3 | 0.0004 | 0.5% | 100.0% |
Rows (staff)
| staff | Mass | Share of inertia | Quality (2 dim.) | Dim. 1 | Contribution 1 | cos² 1 | Dim. 2 | Contribution 2 | cos² 2 |
|---|---|---|---|---|---|---|---|---|---|
| Senior managers | 0.0570 | 3.1% | 0.8926 | 0.0658 | 0.3% | 0.0922 | 0.1937 | 21.4% | 0.8003 |
| Junior managers | 0.0933 | 13.9% | 0.9911 | −0.2590 | 8.4% | 0.5264 | 0.2433 | 55.1% | 0.4647 |
| Senior employees | 0.2642 | 45.0% | 0.9998 | 0.3806 | 51.2% | 0.9990 | 0.0107 | 0.3% | 0.0008 |
| Junior employees | 0.4560 | 30.8% | 0.9998 | −0.2330 | 33.1% | 0.9419 | −0.0577 | 15.2% | 0.0579 |
| Secretaries | 0.1295 | 7.1% | 0.9986 | 0.2011 | 7.0% | 0.8653 | −0.0789 | 8.1% | 0.1333 |
Columns (smoking)
| smoking | Mass | Share of inertia | Quality (2 dim.) | Dim. 1 | Contribution 1 | cos² 1 | Dim. 2 | Contribution 2 | cos² 2 |
|---|---|---|---|---|---|---|---|---|---|
| Non-smoker | 0.3161 | 57.7% | 1.0000 | 0.3933 | 65.4% | 0.9940 | 0.0305 | 2.9% | 0.0060 |
| Light | 0.2332 | 8.3% | 0.9840 | −0.0995 | 3.1% | 0.3267 | −0.1411 | 46.3% | 0.6573 |
| Medium | 0.3212 | 14.8% | 0.9832 | −0.1963 | 16.6% | 0.9818 | −0.0074 | 0.2% | 0.0014 |
| Heavy | 0.1295 | 19.2% | 0.9946 | −0.2938 | 15.0% | 0.6844 | 0.1978 | 50.6% | 0.3102 |
- Principal coordinates in the tables; the map shows both sets in principal coordinates (symmetric map: compare rows with rows and columns with columns, not across). Signs make each dimension's row with the largest absolute coordinate positive; contributions sum to 100% per dimension; cos² is the share of a level's inertia on that dimension.
The exact R script · R R version 4.5.1 (2025-06-13)
# Correspondence analysis (CA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.ca 1.0.0 · spec 2da30e50a0d783b6
# Dataset: rep2_smoke (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep2_smoke.parquet", col_select = c("staff", "smoking", "count")))
n_input <- nrow(df)
df[["staff"]] <- factor(df[["staff"]], levels = c("Senior managers", "Junior managers", "Senior employees", "Junior employees", "Secretaries")) # stored level order
df[["smoking"]] <- factor(df[["smoking"]], levels = c("Non-smoker", "Light", "Medium", "Heavy")) # stored level order
df <- df[stats::complete.cases(df[c("staff", "smoking", "count")]), , 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("staff", "smoking", "count")) # infinite values stop the run (registry/errors.yaml)
# %% Analysis
# Correspondence analysis (Benzécri 1973; Greenacre 2017): the χ² distances between the row profiles and
# between the column profiles of a two-way table, shown on a few dimensions from the SVD of the
# standardized residuals.
row_var <- "staff"
col_var <- "smoking"
count_var <- "count"
K_REQ <- as.integer(2)
MAP <- "symmetric" # symmetric | row_principal | column_principal
alpha <- 0.05
w <- if (!is.null(count_var)) as.double(df[[count_var]]) else rep(1, nrow(df))
if (!is.null(count_var) && any(w < 0)) cs_error("CS_E_INVALID_VALUES", column = count_var, requirement = "non-negative counts", count = sum(w < 0))
row_levels <- levels(df[[row_var]])
col_levels <- levels(df[[col_var]])
N <- matrix(0, length(row_levels), length(col_levels))
ri <- as.integer(df[[row_var]])
ci <- as.integer(df[[col_var]])
for (t in seq_along(w)) N[ri[t], ci[t]] <- N[ri[t], ci[t]] + w[t]
keep_r <- rowSums(N) > 0
keep_c <- colSums(N) > 0
notes <- character(0)
if (!all(keep_r) || !all(keep_c)) {
notes <- c(notes, sprintf("Levels with a total count of zero were left out: %s.", paste(c(row_levels[!keep_r], col_levels[!keep_c]), collapse = ", ")))
}
N <- N[keep_r, keep_c, drop = FALSE]
row_levels <- row_levels[keep_r]
col_levels <- col_levels[keep_c]
cs_check_groups(row_levels, row_var, minimum = 2)
cs_check_groups(col_levels, col_var, minimum = 2)
fit <- cs_mview_ca(N)
dims <- fit$dims
K <- min(K_REQ, dims)
total <- fit$total
share <- if (total > 0) fit$eigen / total else rep(NaN, dims)
df_chi <- (length(row_levels) - 1) * (length(col_levels) - 1)
p_chi <- stats::pchisq(fit$chisq, df_chi, lower.tail = FALSE)
expected <- outer(rowSums(N), colSums(N)) / fit$n
# %% Assumptions
small <- mean(expected < 5)
ok_exp <- small <= 0.2 && min(expected) >= 1
assumptions <- list(
list(key = "expected", label = "Expected counts (for the χ² p-value)", status = if (ok_exp) "ok" else "warn",
detail = paste0(sprintf("%.0f%% of cells expect fewer than 5 (smallest %s). ", 100 * small, format(signif(min(expected), 2))),
if (ok_exp) "The χ² p-value is reliable."
else "The χ² p-value is approximate; the map itself does not depend on it, but rare levels can dominate a dimension — check their contributions.")),
list(key = "profiles", label = "Counts of independent units", status = "info",
detail = "CA describes the table; the χ² test treats every count as an independent unit.")
)
# %% Result
values <- list(n = fit$n, n_rows = length(row_levels), n_cols = length(col_levels), dims = dims,
total_inertia = total, chisq = fit$chisq, df = df_chi, p = p_chi,
cum2 = if (total > 0) sum(share[seq_len(min(2, dims))]) else NaN)
for (j in seq_len(dims)) {
values[[sprintf("eigen[%d]", j)]] <- fit$eigen[j]
values[[sprintf("share[%d]", j)]] <- share[j]
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
cum <- cumsum(share)
tables <- list(list(key = "inertia", title = "Principal inertias",
columns = list(list(key = "dimension", label = "Dimension", type = "integer"), list(key = "eigen", label = "Principal inertia", type = "number"),
list(key = "share", label = "Share", type = "percent"), list(key = "cumulative", label = "Cumulative", type = "percent")),
rows = lapply(seq_len(dims), function(j) list(dimension = j, eigen = fit$eigen[j], share = share[j], cumulative = cum[j]))))
side_table <- function(key, title, var, levs, mass, inertia, coord, ctr, cos2) {
cols <- list(list(key = "level", label = var, type = "string"), list(key = "mass", label = "Mass", type = "number"),
list(key = "inertia", label = "Share of inertia", type = "percent"), list(key = "quality", label = sprintf("Quality (%d dim.)", K), type = "number"))
for (j in seq_len(K)) {
cols <- c(cols, list(list(key = sprintf("coord%d", j), label = sprintf("Dim. %d", j), type = "number"),
list(key = sprintf("ctr%d", j), label = sprintf("Contribution %d", j), type = "percent"),
list(key = sprintf("cos%d", j), label = sprintf("cos² %d", j), type = "number")))
}
rows <- lapply(seq_along(levs), function(i) {
cq <- cos2[i, seq_len(K)]
row <- list(level = levs[i], mass = mass[i], inertia = if (total > 0) inertia[i] / total else NaN,
quality = if (all(is.nan(cq))) NaN else sum(cq, na.rm = TRUE))
for (j in seq_len(K)) {
row[[sprintf("coord%d", j)]] <- coord[i, j]
row[[sprintf("ctr%d", j)]] <- ctr[i, j]
row[[sprintf("cos%d", j)]] <- cos2[i, j]
}
row
})
list(key = key, title = title, columns = cols, rows = rows)
}
tables[[2]] <- side_table("rows", sprintf("Rows (%s)", row_var), row_var, row_levels, fit$row_mass, fit$row_inertia, fit$row_coord, fit$row_ctr, fit$row_cos2)
tables[[3]] <- side_table("cols", sprintf("Columns (%s)", col_var), col_var, col_levels, fit$col_mass, fit$col_inertia, fit$col_coord, fit$col_ctr, fit$col_cos2)
charts <- list(cs_chart("scree", "scree-plot", "Principal inertias", list(
component = cs_col("Dimension", as.double(seq_len(dims))),
variance = cs_col("Share of inertia", share),
cumulative = cs_col("Cumulative share", cum))))
if (dims >= 2 && K >= 2) {
rc <- if (MAP %in% c("symmetric", "row_principal")) fit$row_coord else fit$row_std
cc <- if (MAP %in% c("symmetric", "column_principal")) fit$col_coord else fit$col_std
charts <- c(list(cs_chart("map", "ca-map", "Correspondence analysis map", list(
x = cs_col(sprintf("Dimension 1 (%.1f%%)", 100 * share[1]), c(rc[, 1], cc[, 1])),
y = cs_col(sprintf("Dimension 2 (%.1f%%)", 100 * share[2]), c(rc[, 2], cc[, 2])),
set = cs_col("Set", c(rep(row_var, length(row_levels)), rep(col_var, length(col_levels))), "categorical"),
label = cs_col("Level", c(row_levels, col_levels), "categorical"),
mass = cs_col("Mass", c(fit$row_mass, fit$col_mass))), controls = list(map = MAP))), charts)
}
summary <- paste0(sprintf("Correspondence analysis of %s (%d levels) by %s (%d levels), total count %s: total inertia %.4f (χ² = %.2f, df = %d, %s). ",
row_var, length(row_levels), col_var, length(col_levels), format(fit$n), total, fit$chisq, as.integer(df_chi), cs_fmt_p(p_chi)),
if (dims >= 2) sprintf("The first two dimensions show %.1f%% and %.1f%% of it (%.1f%% together).", 100 * share[1], 100 * share[2], 100 * (share[1] + share[2]))
else "The one dimension shows all of it.")
map_note <- switch(MAP,
symmetric = "both sets in principal coordinates (symmetric map: compare rows with rows and columns with columns, not across)",
row_principal = "rows in principal and columns in standard coordinates (row-principal biplot)",
"columns in principal and rows in standard coordinates (column-principal biplot)")
cs_publish(list(
method = "contingency.ca",
methodVersion = "1.0.0",
title = "Correspondence analysis",
engine = cs_engine_info("stats", "nanoparquet"),
n = fit$n,
summary = summary,
apa = sprintf("Correspondence analysis, total inertia = %.3f, χ²(%d) = %.2f, %s", total, as.integer(df_chi), fit$chisq, cs_fmt_p(p_chi)),
statistics = list(list(key = "total_inertia", label = "Total inertia", value = total),
list(key = "chisq", label = "χ²", value = fit$chisq), list(key = "p", label = "p", value = p_chi, format = "p"),
list(key = "cum2", label = "Shown by 2 dimensions", value = values$cum2, format = "percent")),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = as.list(c(notes, paste0("Principal coordinates in the tables; the map shows ", map_note, ". ",
"Signs make each dimension's row with the largest absolute coordinate positive; contributions sum to 100% per dimension; cos² is the share of a level's inertia on that dimension."))),
values = values,
charts = charts
))
Correspondence analysis, total inertia = 0.085, χ²(12) = 16.44, p = .172
- Total inertia
- 0.0852
- χ²
- 16.442
- p
- .172
- Shown by 2 dimensions
- 99.5%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Expected counts (for the χ² p-value) — 35% of cells expect fewer than 5 (smallest 1.4). The χ² p-value is approximate; the map itself does not depend on it, but rare levels can dominate a dimension — check their contributions.
- Counts of independent units — CA describes the table; the χ² test treats every count as an independent unit.
Principal inertias
| Dimension | Principal inertia | Share | Cumulative |
|---|---|---|---|
| 1 | 0.0748 | 87.8% | 87.8% |
| 2 | 0.0100 | 11.8% | 99.5% |
| 3 | 0.0004 | 0.5% | 100.0% |
Rows (staff)
| staff | Mass | Share of inertia | Quality (2 dim.) | Dim. 1 | Contribution 1 | cos² 1 | Dim. 2 | Contribution 2 | cos² 2 |
|---|---|---|---|---|---|---|---|---|---|
| Senior managers | 0.0570 | 3.1% | 0.8926 | 0.0658 | 0.3% | 0.0922 | 0.1937 | 21.4% | 0.8003 |
| Junior managers | 0.0933 | 13.9% | 0.9911 | −0.2590 | 8.4% | 0.5264 | 0.2433 | 55.1% | 0.4647 |
| Senior employees | 0.2642 | 45.0% | 0.9998 | 0.3806 | 51.2% | 0.9990 | 0.0107 | 0.3% | 0.0008 |
| Junior employees | 0.4560 | 30.8% | 0.9998 | −0.2330 | 33.1% | 0.9419 | −0.0577 | 15.2% | 0.0579 |
| Secretaries | 0.1295 | 7.1% | 0.9986 | 0.2011 | 7.0% | 0.8653 | −0.0789 | 8.1% | 0.1333 |
Columns (smoking)
| smoking | Mass | Share of inertia | Quality (2 dim.) | Dim. 1 | Contribution 1 | cos² 1 | Dim. 2 | Contribution 2 | cos² 2 |
|---|---|---|---|---|---|---|---|---|---|
| Non-smoker | 0.3161 | 57.7% | 1.0000 | 0.3933 | 65.4% | 0.9940 | 0.0305 | 2.9% | 0.0060 |
| Light | 0.2332 | 8.3% | 0.9840 | −0.0995 | 3.1% | 0.3267 | −0.1411 | 46.3% | 0.6573 |
| Medium | 0.3212 | 14.8% | 0.9832 | −0.1963 | 16.6% | 0.9818 | −0.0074 | 0.2% | 0.0014 |
| Heavy | 0.1295 | 19.2% | 0.9946 | −0.2938 | 15.0% | 0.6844 | 0.1978 | 50.6% | 0.3102 |
- Principal coordinates in the tables; the map shows both sets in principal coordinates (symmetric map: compare rows with rows and columns with columns, not across). Signs make each dimension's row with the largest absolute coordinate positive; contributions sum to 100% per dimension; cos² is the share of a level's inertia on that dimension.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Correspondence analysis (CA)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method contingency.ca 1.0.0 · spec 2da30e50a0d783b6
# Dataset: rep2_smoke (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
from scipy import stats
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant
from codesplash.stats import multiview as mvw
# %% Data
df = pd.read_parquet("tests/parity/fixtures/rep2_smoke.parquet", columns=["staff", "smoking", "count"])
n_input = len(df)
df["staff"] = pd.Categorical(df["staff"], categories=["Senior managers", "Junior managers", "Senior employees", "Junior employees", "Secretaries"]) # stored level order
df["smoking"] = pd.Categorical(df["smoking"], categories=["Non-smoker", "Light", "Medium", "Heavy"]) # stored level order
df = df.dropna(subset=["staff", "smoking", "count"]) # listwise deletion over the analysis columns
df["staff"] = df["staff"].cat.remove_unused_categories()
df["smoking"] = df["smoking"].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, ["staff", "smoking", "count"]) # infinite values stop the run (registry/errors.yaml)
# %% Analysis
# Correspondence analysis (Benzécri 1973; Greenacre 2017): the χ² distances between the row profiles and
# between the column profiles of a two-way table, shown on a few dimensions from the SVD of the
# standardized residuals.
row_var = "staff"
col_var = "smoking"
count_var = "count"
K_REQ = int(2)
MAP = "symmetric" # symmetric | row_principal | column_principal
alpha = 0.05
w = df[count_var].to_numpy(dtype=float) if count_var else np.ones(len(df))
if count_var and np.any(w < 0):
cs.cs_error("CS_E_INVALID_VALUES", column=count_var, requirement="non-negative counts", count=int(np.sum(w < 0)))
row_levels = [str(x) for x in df[row_var].cat.categories]
col_levels = [str(x) for x in df[col_var].cat.categories]
N = np.zeros((len(row_levels), len(col_levels)))
np.add.at(N, (df[row_var].cat.codes.to_numpy(), df[col_var].cat.codes.to_numpy()), w)
keep_r = N.sum(axis=1) > 0
keep_c = N.sum(axis=0) > 0
notes = []
if not keep_r.all() or not keep_c.all():
gone = [row_levels[i] for i in np.flatnonzero(~keep_r)] + [col_levels[j] for j in np.flatnonzero(~keep_c)]
notes.append(f"Levels with a total count of zero were left out: {', '.join(gone)}.")
N = N[keep_r][:, keep_c]
row_levels = [lv for lv, k_ in zip(row_levels, keep_r) if k_]
col_levels = [lv for lv, k_ in zip(col_levels, keep_c) if k_]
check_groups(row_levels, row_var, minimum=2)
check_groups(col_levels, col_var, minimum=2)
fit = mvw.ca(N)
dims = fit["dims"]
K = min(K_REQ, dims)
total = fit["total"]
share = fit["eigen"] / total if total > 0 else np.full(dims, np.nan)
df_chi = (len(row_levels) - 1) * (len(col_levels) - 1)
p_chi = float(stats.chi2.sf(fit["chisq"], df_chi))
expected = np.outer(N.sum(axis=1), N.sum(axis=0)) / fit["n"]
# %% Assumptions
small = float(np.mean(expected < 5))
assumptions = [
{"key": "expected", "label": "Expected counts (for the χ² p-value)", "status": "ok" if small <= 0.2 and expected.min() >= 1 else "warn",
"detail": f"{small:.0%} of cells expect fewer than 5 (smallest {expected.min():.2g}). " + ("The χ² p-value is reliable." if small <= 0.2 and expected.min() >= 1
else "The χ² p-value is approximate; the map itself does not depend on it, but rare levels can dominate a dimension — check their contributions.")},
{"key": "profiles", "label": "Counts of independent units", "status": "info",
"detail": "CA describes the table; the χ² test treats every count as an independent unit."},
]
# %% Result
values = {"n": fit["n"], "n_rows": len(row_levels), "n_cols": len(col_levels), "dims": dims,
"total_inertia": total, "chisq": fit["chisq"], "df": df_chi, "p": p_chi,
"cum2": float(np.sum(share[:2])) if total > 0 else float("nan")}
for j in range(dims):
values[f"eigen[{j + 1}]"] = float(fit["eigen"][j])
values[f"share[{j + 1}]"] = float(share[j])
values["missing_share"] = n_dropped / n_input if n_input else 0.0
cum = np.cumsum(share)
tables = [{"key": "inertia", "title": "Principal inertias",
"columns": [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "eigen", "label": "Principal inertia", "type": "number"},
{"key": "share", "label": "Share", "type": "percent"}, {"key": "cumulative", "label": "Cumulative", "type": "percent"}],
"rows": [{"dimension": j + 1, "eigen": float(fit["eigen"][j]), "share": float(share[j]), "cumulative": float(cum[j])} for j in range(dims)]}]
def side_table(key, title, var, levels, mass, inertia, coord, ctr, cos2):
cols = [{"key": "level", "label": var, "type": "string"}, {"key": "mass", "label": "Mass", "type": "number"},
{"key": "inertia", "label": "Share of inertia", "type": "percent"}, {"key": "quality", "label": f"Quality ({K} dim.)", "type": "number"}]
for j in range(K):
cols += [{"key": f"coord{j + 1}", "label": f"Dim. {j + 1}", "type": "number"},
{"key": f"ctr{j + 1}", "label": f"Contribution {j + 1}", "type": "percent"},
{"key": f"cos{j + 1}", "label": f"cos² {j + 1}", "type": "number"}]
rows = []
for i, lv in enumerate(levels):
row = {"level": lv, "mass": float(mass[i]), "inertia": float(inertia[i] / total) if total > 0 else float("nan"),
"quality": float(np.nansum(cos2[i, :K])) if not np.all(np.isnan(cos2[i, :K])) else float("nan")}
for j in range(K):
row.update({f"coord{j + 1}": float(coord[i, j]), f"ctr{j + 1}": float(ctr[i, j]), f"cos{j + 1}": float(cos2[i, j])})
rows.append(row)
return {"key": key, "title": title, "columns": cols, "rows": rows}
tables.append(side_table("rows", f"Rows ({row_var})", row_var, row_levels, fit["row_mass"], fit["row_inertia"], fit["row_coord"], fit["row_ctr"], fit["row_cos2"]))
tables.append(side_table("cols", f"Columns ({col_var})", col_var, col_levels, fit["col_mass"], fit["col_inertia"], fit["col_coord"], fit["col_ctr"], fit["col_cos2"]))
charts = [cs.chart("scree", "scree-plot", "Principal inertias", {
"component": cs.col("Dimension", np.arange(1, dims + 1, dtype=float)),
"variance": cs.col("Share of inertia", share),
"cumulative": cs.col("Cumulative share", cum)})]
if dims >= 2 and K >= 2:
rc = fit["row_coord"] if MAP in ("symmetric", "row_principal") else fit["row_std"]
cc = fit["col_coord"] if MAP in ("symmetric", "column_principal") else fit["col_std"]
charts.insert(0, cs.chart("map", "ca-map", "Correspondence analysis map", {
"x": cs.col(f"Dimension 1 ({share[0]:.1%})", np.concatenate([rc[:, 0], cc[:, 0]])),
"y": cs.col(f"Dimension 2 ({share[1]:.1%})", np.concatenate([rc[:, 1], cc[:, 1]])),
"set": cs.col("Set", [row_var] * len(row_levels) + [col_var] * len(col_levels), "categorical"),
"label": cs.col("Level", row_levels + col_levels, "categorical"),
"mass": cs.col("Mass", np.concatenate([fit["row_mass"], fit["col_mass"]]))},
controls={"map": MAP}))
summary = (f"Correspondence analysis of {row_var} ({len(row_levels)} levels) by {col_var} ({len(col_levels)} levels), total count {fit['n']:g}: "
f"total inertia {total:.4f} (χ² = {fit['chisq']:.2f}, df = {df_chi}, {cs.fmt_p(p_chi)}). "
+ (f"The first two dimensions show {share[0]:.1%} and {share[1]:.1%} of it ({share[0] + share[1]:.1%} together)." if dims >= 2
else f"The one dimension shows all of it."))
cs.publish({
"method": "contingency.ca",
"methodVersion": "1.0.0",
"title": "Correspondence analysis",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": int(round(fit["n"])) if float(fit["n"]).is_integer() else fit["n"],
"summary": summary,
"apa": f"Correspondence analysis, total inertia = {total:.3f}, χ²({df_chi}) = {fit['chisq']:.2f}, {cs.fmt_p(p_chi)}",
"statistics": [{"key": "total_inertia", "label": "Total inertia", "value": total},
{"key": "chisq", "label": "χ²", "value": fit["chisq"]}, {"key": "p", "label": "p", "value": p_chi, "format": "p"},
{"key": "cum2", "label": "Shown by 2 dimensions", "value": values["cum2"], "format": "percent"}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes + [f"Principal coordinates in the tables; the map shows {'both sets in principal coordinates (symmetric map: compare rows with rows and columns with columns, not across)' if MAP == 'symmetric' else ('rows in principal and columns in standard coordinates (row-principal biplot)' if MAP == 'row_principal' else 'columns in principal and rows in standard coordinates (column-principal biplot)')}. "
"Signs make each dimension's row with the largest absolute coordinate positive; contributions sum to 100% per dimension; cos² is the share of a level's inertia on that dimension."],
"values": values,
"charts": charts,
})
Greenacre's classic table: 193 staff in five groups by smoking habit, entered as one row per cell with a count column. The total inertiaInertia (correspondence analysis)Total inertia is χ²/n, the table's departure from independence; each dimension's principal inertia is its share of it. is 0.0852, which is χ² divided by the total count (χ² = 16.4).
The first dimension shows 87.8% of the inertia and the first two together 99.5%. So the two-dimensional map shows nearly all of the association.
View data
| Dimension 1 (87.8%) | Dimension 2 (11.8%) | set | level | mass |
|---|---|---|---|---|
| 0.0658 | 0.1937 | staff group | Senior managers | 0.0570 |
| −0.2590 | 0.2433 | staff group | Junior managers | 0.0933 |
| 0.3806 | 0.0107 | staff group | Senior employees | 0.2642 |
| −0.2330 | −0.0577 | staff group | Junior employees | 0.4560 |
| 0.2011 | −0.0789 | staff group | Secretaries | 0.1295 |
| 0.3933 | 0.0305 | smoking | Non-smoker | 0.3161 |
| −0.0995 | −0.1411 | smoking | Light | 0.2332 |
| −0.1963 | −0.0074 | smoking | Medium | 0.3212 |
| −0.2938 | 0.1978 | smoking | Heavy | 0.1295 |
Reading the map
ReadThe center is the average profile. A level far from it differs most from the average. On the first dimension, non-smokers sit opposite the light, medium and heavy smokers, and senior employees lean toward the non-smoking side.
In this symmetric map, compare rows with rows and columns with columns. The distance from a row point to a column point isn't defined there. To read rows against columns, choose Rows principal: a row then sits toward the columns it has more of.
Make a guess
PredictPredict first
A table has 4 rows and 2 columns. How many dimensions can correspondence analysis find?
Reveal
One. CA finds min(rows, columns) − 1 dimensions. The housing table of type by contact has 1 dimension, so its map is a line and the app shows the inertia table instead.
Before naming a dimension
ReadTwo numbers per level keep you honest:
- Contribution: the level's share of a dimension's inertia. Name the dimension from the levels that contribute most.
- cos²: the share of the level's own inertia that the dimension shows. A level with low cos² on the map is shown poorly, so its position there can mislead.
Check your understanding
CheckpointCheck yourself
What does the total inertia of a correspondence analysis measure?
Show the answer
Answer: b
Total inertia is χ²/n. Each dimension shows part of it, and the shares add up to 100%.
Check yourself
In a symmetric map, the row point "Secretaries" lies right next to the column point "Medium". What can you conclude?
Show the answer
Answer: b
Row-to-column closeness suggests a link, but check it in the table or switch to a biplot map, where directions between rows and columns can be read.
Check yourself
A level has a large contribution to dimension 1 but a cos² of 0.2 on it. What does that mean?
Show the answer
Answer: a
Contribution is about the dimension; cos² is about the level. A low cos² means the map's first dimension shows only a fifth of that level's own inertia.
Concepts in this lesson