The Mantel test: two sets of distances
Correlate two dissimilarity matrices, see why pairs can't be treated as independent, and use partial Mantel and correlograms with their real limits in mind.
What runs in CodeSplash
- STAT254Mantel permutation test Runs in CodeSplash
- Mantel test (and partial Mantel, correlogram) Verified in Python and R
You will be able to
- Explain what a Mantel r measures and why the test shuffles rows, not pairs
- Read a distance–distance plot and the permutation quantiles
- State the limits of partial Mantel tests and Mantel correlograms
Two tables, one question
ReadTwenty-four lichen pastures have a table of plant species and a table of soil chemistry. Do pastures that are similar in soil also tend to be similar in plants?
The Mantel testMantel testThe correlation between two dissimilarity matrices on the same objects, tested by permuting whole rows of one. builds one dissimilarity matrix for each table, then correlates their entries.
Note what this measures: it relates distances to distances, not soil values to plant values.
How many pairs are there?
PredictPredict first
With 24 pastures, how many entries go into that correlation?
Would an ordinary correlation test on them be valid?
Reveal
276 pairs, which is . An ordinary test would be far too optimistic. All the pairs that involve one pasture depend on that one pasture, so there are many fewer independent pieces of information than pairs. The Mantel test shuffles whole rows of one table to respect that.
Read a result
In the appMantel test, r_M = 0.30, p = .005
- r_M
- 0.3047
- p
- .005
- Pairs
- 276
Effect size
- Mantel r 0.3047
Plots
View data
| Euclidean dissimilarity of N, P, K, Ca, Mg, S, Al, Fe, Mn, Zn, Mo, Baresoil, Humdepth, pH | Bray–Curtis dissimilarity of Callvulg, Empenigr, Rhodtome, Vaccmyrt, Vaccviti, Pinusylv, Descflex, Betupube, Vacculig, Diphcomp, Dicrsp, Dicrfusc, Dicrpoly, Hylosple, Pleuschr, Polypili, Polyjuni, Polycomm, Pohlnuta, Ptilcili, Barbhatc, Cladarbu, Cladrang, Cladstel, Cladunci, Cladcocc, Cladcorn, Cladgrac, Cladfimb, Cladcris, Cladchlo, Cladbotr, Cladamau, Cladsp, Cetreric, Cetrisla, Flavniva, Nepharct, Stersp, Peltapht, Icmaeric, Cladcerv, Claddefo, Cladphyl |
|---|---|
| 2.077 | 0.5310 |
| 6.881 | 0.6681 |
| 4.473 | 0.5621 |
| 2.508 | 0.3747 |
| 3.580 | 0.5095 |
| 2.659 | 0.6234 |
| 2.296 | 0.5338 |
| 4.712 | 0.8418 |
| 5.163 | 0.3453 |
| 2.214 | 0.5450 |
| 3.930 | 0.3879 |
| 3.134 | 0.6319 |
| 4.903 | 0.3604 |
| 5.495 | 0.4956 |
| 4.241 | 0.3382 |
| 6.114 | 0.5277 |
| 6.056 | 0.4694 |
| 4.952 | 0.5724 |
| 4.211 | 0.6584 |
| 2.859 | 0.4688 |
| 4.972 | 0.6249 |
| 6.555 | 0.4459 |
| 2.541 | 0.5561 |
| 6.903 | 0.3598 |
| 4.640 | 0.4056 |
| 3.725 | 0.3652 |
| 4.231 | 0.4561 |
| 3.322 | 0.3580 |
| 2.523 | 0.3977 |
| 5.136 | 0.5225 |
| 5.144 | 0.6064 |
| 2.509 | 0.4804 |
| 4.723 | 0.3784 |
| 3.439 | 0.3376 |
| 4.852 | 0.6717 |
| 5.503 | 0.7179 |
| 3.522 | 0.6355 |
| 5.875 | 0.7579 |
| 5.491 | 0.6844 |
| 4.272 | 0.8206 |
| 3.153 | 0.7761 |
| 1.748 | 0.6794 |
| 4.124 | 0.7645 |
| 6.159 | 0.4716 |
| 3.351 | 0.7607 |
| 5.480 | 0.4935 |
| 5.714 | 0.5020 |
| 5.445 | 0.5092 |
| 6.211 | 0.5010 |
| 7.579 | 0.5908 |
| 5.728 | 0.5737 |
| 5.503 | 0.7577 |
| 6.052 | 0.6534 |
| 5.138 | 0.4347 |
| 6.818 | 0.3369 |
| 8.766 | 0.7931 |
| 9.044 | 0.8562 |
| 8.340 | 0.7441 |
| 9.114 | 0.8382 |
| 5.675 | 0.8310 |
First 60 of 276 rows.
Assumptions
- Linear relation between the dissimilarities — The Mantel r measures a linear (Pearson) or monotone (Spearman) relation between pairwise dissimilarities, not between the raw variables.
- Exchangeable objects — Rows are permuted as whole objects; with spatial or temporal structure in both matrices the permutation p is too small (Legendre, Fortin & Borcard 2015).
Upper quantiles of the permutation distribution
| Quantile | r_M |
|---|---|
| 90% | 0.1054 |
| 95% | 0.1362 |
| 97.5% | 0.1500 |
| 99% | 0.1800 |
- Mantel r over 276 pairs of rows; greater p from 199 row permutations of the first matrix (seed 42).
The exact R script · R R version 4.5.1 (2025-06-13)
# Mantel test (and partial Mantel, correlogram)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.mantel 1.0.1 · spec adb6f94682fb279f
# Dataset: mv_vare (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/mv_vare.parquet", col_select = c("Callvulg", "Empenigr", "Rhodtome", "Vaccmyrt", "Vaccviti", "Pinusylv", "Descflex", "Betupube", "Vacculig", "Diphcomp", "Dicrsp", "Dicrfusc", "Dicrpoly", "Hylosple", "Pleuschr", "Polypili", "Polyjuni", "Polycomm", "Pohlnuta", "Ptilcili", "Barbhatc", "Cladarbu", "Cladrang", "Cladstel", "Cladunci", "Cladcocc", "Cladcorn", "Cladgrac", "Cladfimb", "Cladcris", "Cladchlo", "Cladbotr", "Cladamau", "Cladsp", "Cetreric", "Cetrisla", "Flavniva", "Nepharct", "Stersp", "Peltapht", "Icmaeric", "Cladcerv", "Claddefo", "Cladphyl", "N", "P", "K", "Ca", "Mg", "S", "Al", "Fe", "Mn", "Zn", "Mo", "Baresoil", "Humdepth", "pH")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Callvulg", "Empenigr", "Rhodtome", "Vaccmyrt", "Vaccviti", "Pinusylv", "Descflex", "Betupube", "Vacculig", "Diphcomp", "Dicrsp", "Dicrfusc", "Dicrpoly", "Hylosple", "Pleuschr", "Polypili", "Polyjuni", "Polycomm", "Pohlnuta", "Ptilcili", "Barbhatc", "Cladarbu", "Cladrang", "Cladstel", "Cladunci", "Cladcocc", "Cladcorn", "Cladgrac", "Cladfimb", "Cladcris", "Cladchlo", "Cladbotr", "Cladamau", "Cladsp", "Cetreric", "Cetrisla", "Flavniva", "Nepharct", "Stersp", "Peltapht", "Icmaeric", "Cladcerv", "Claddefo", "Cladphyl", "N", "P", "K", "Ca", "Mg", "S", "Al", "Fe", "Mn", "Zn", "Mo", "Baresoil", "Humdepth", "pH")]), , 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("Callvulg", "Empenigr", "Rhodtome", "Vaccmyrt", "Vaccviti", "Pinusylv", "Descflex", "Betupube", "Vacculig", "Diphcomp", "Dicrsp", "Dicrfusc", "Dicrpoly", "Hylosple", "Pleuschr", "Polypili", "Polyjuni", "Polycomm", "Pohlnuta", "Ptilcili", "Barbhatc", "Cladarbu", "Cladrang", "Cladstel", "Cladunci", "Cladcocc", "Cladcorn", "Cladgrac", "Cladfimb", "Cladcris", "Cladchlo", "Cladbotr", "Cladamau", "Cladsp", "Cetreric", "Cetrisla", "Flavniva", "Nepharct", "Stersp", "Peltapht", "Icmaeric", "Cladcerv", "Claddefo", "Cladphyl", "N", "P", "K", "Ca", "Mg", "S", "Al", "Fe", "Mn", "Zn", "Mo", "Baresoil", "Humdepth", "pH")) # infinite values stop the run (registry/errors.yaml)
# %% Test
# Mantel test (Mantel 1967): correlation between the dissimilarities of two sets of variables measured on
# the same rows, p by permuting the rows (and columns) of the first matrix together. A third set gives the
# partial Mantel test (Smouse, Long & Sokal 1986); the correlogram tests distance classes of the second.
x_vars <- c("Callvulg", "Empenigr", "Rhodtome", "Vaccmyrt", "Vaccviti", "Pinusylv", "Descflex", "Betupube", "Vacculig", "Diphcomp", "Dicrsp", "Dicrfusc", "Dicrpoly", "Hylosple", "Pleuschr", "Polypili", "Polyjuni", "Polycomm", "Pohlnuta", "Ptilcili", "Barbhatc", "Cladarbu", "Cladrang", "Cladstel", "Cladunci", "Cladcocc", "Cladcorn", "Cladgrac", "Cladfimb", "Cladcris", "Cladchlo", "Cladbotr", "Cladamau", "Cladsp", "Cetreric", "Cetrisla", "Flavniva", "Nepharct", "Stersp", "Peltapht", "Icmaeric", "Cladcerv", "Claddefo", "Cladphyl")
y_vars <- c("N", "P", "K", "Ca", "Mg", "S", "Al", "Fe", "Mn", "Zn", "Mo", "Baresoil", "Humdepth", "pH")
z_vars <- character(0)
x_metric <- "bray"
y_metric <- "euclidean"
x_transform <- "none"
y_transform <- "standardize"
method <- "pearson" # pearson | spearman
alternative <- "greater" # greater | two_sided | less
correlogram <- FALSE
n_classes <- as.integer(0)
seed <- 42
n_perm <- as.integer(199)
alpha <- 0.05
DIST_LABEL <- c(euclidean = "Euclidean", manhattan = "Manhattan", bray = "Bray–Curtis", jaccard = "Jaccard", gower = "Gower")
n <- nrow(df)
if (n > 3000) stop(sprintf("The Mantel test uses n × n matrices; %d rows is too many (at most 3000).", n))
if (n < 5) cs_error("CS_E_TOO_FEW_ROWS", what = "The Mantel test", min = 5, n = n)
A <- cs_mvd_distance(cs_mvd_transform(as.matrix(df[x_vars]), x_transform), x_metric)
B <- cs_mvd_distance(cs_mvd_transform(as.matrix(df[y_vars]), y_transform), y_metric)
C <- if (length(z_vars)) cs_mvd_distance(cs_mvd_transform(as.matrix(df[z_vars]), "standardize"), "euclidean") else NULL
res <- cs_mvd_mantel(A, B, C, method, alternative, n_perm, seed)
r <- res$r
p <- res$p
cg <- if (correlogram) cs_mvd_correlogram(A, B, n_classes, method, n_perm, seed) else NULL
# %% Assumptions
assumptions <- list(
list(key = "linear", label = "Linear relation between the dissimilarities", status = "info",
detail = "The Mantel r measures a linear (Pearson) or monotone (Spearman) relation between pairwise dissimilarities, not between the raw variables."),
list(key = "exchangeable", label = "Exchangeable objects", status = "info",
detail = "Rows are permuted as whole objects; with spatial or temporal structure in both matrices the permutation p is too small (Legendre, Fortin & Borcard 2015).")
)
# %% Result
kind <- if (!is.null(C)) "partial Mantel" else "Mantel"
xs <- paste(x_vars, collapse = ", ")
ys <- paste(y_vars, collapse = ", ")
cond <- if (!is.null(C)) paste0(", controlling for ", paste(z_vars, collapse = ", ")) else ""
summary <- paste0(sprintf("The %s test (%s) between the %s dissimilarities of %s and the %s dissimilarities of %s%s: r_M = %.3f, %s (%d permutations) — ",
kind, if (method == "spearman") "Spearman" else "Pearson", DIST_LABEL[[x_metric]], xs, DIST_LABEL[[y_metric]], ys, cond, r, cs_fmt_p(p), n_perm),
if (p < alpha) sprintf("pairs of rows that differ more in one set differ %s in the other.", if (r > 0) "more" else "less")
else "no evidence that the two sets of dissimilarities are related.")
values <- list(r = r, p = p, n = n, pairs = res$pairs, n_perm = n_perm, partial = !is.null(C),
q90 = res$quantiles[1], q95 = res$quantiles[2], q975 = res$quantiles[3], q99 = res$quantiles[4])
tables <- list(list(key = "null", title = "Upper quantiles of the permutation distribution",
columns = list(list(key = "q", label = "Quantile", type = "string"), list(key = "value", label = "r_M", type = "number")),
rows = data.frame(q = c("90%", "95%", "97.5%", "99%"), value = res$quantiles)))
pr <- cs_mvd_pairs(n)
pick <- unique(round(seq(1, length(pr$i), length.out = min(length(pr$i), 5000))))
charts <- list(cs_chart("pairs", "distance-distance", "Dissimilarity pairs", list(
x = cs_col(sprintf("%s dissimilarity of %s", DIST_LABEL[[y_metric]], ys), B[cbind(pr$i[pick], pr$j[pick])]),
y = cs_col(sprintf("%s dissimilarity of %s", DIST_LABEL[[x_metric]], xs), A[cbind(pr$i[pick], pr$j[pick])])), controls = list(line = TRUE)))
if (!is.null(cg)) {
rows <- cg$classes
for (row in rows) {
values[[sprintf("class_r[%d]", as.integer(row$class))]] <- row$r
values[[sprintf("class_p[%d]", as.integer(row$class))]] <- row$p_adj
}
tables[[2]] <- list(key = "correlogram", title = sprintf("Mantel correlogram over %d distance classes of %s", as.integer(cg$n_classes), ys),
columns = list(list(key = "class", label = "Class", type = "integer"), list(key = "from", label = "From", type = "number"),
list(key = "to", label = "To", type = "number"), list(key = "pairs", label = "Pairs", type = "integer"),
list(key = "r", label = "r_M", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "p_adj", label = "Progressive p", type = "pvalue")),
rows = lapply(rows, function(row) row[c("class", "from", "to", "pairs", "r", "p", "p_adj")]))
ok <- Filter(function(row) !is.nan(row$r), rows)
charts[[2]] <- cs_chart("correlogram", "mantel-correlogram", sprintf("Mantel correlogram: similarity of %s by distance class of %s", xs, ys), list(
mid = cs_col(sprintf("Distance class of %s", ys), vapply(ok, `[[`, 0, "mid")),
r = cs_col("Mantel r", vapply(ok, `[[`, 0, "r")),
p = cs_col("Progressive p", vapply(ok, `[[`, 0, "p_adj")),
pairs = cs_col("Pairs", as.numeric(vapply(ok, `[[`, 0, "pairs")))), controls = list(alpha = alpha))
first_pos <- Find(function(row) !is.nan(row$r) && row$r > 0 && row$p_adj < alpha, rows)
summary <- paste(summary, if (!is.null(first_pos))
sprintf("Correlogram: rows within the first significant class (%s–%s) are more similar than average.", format(signif(first_pos$from, 3)), format(signif(first_pos$to, 3)))
else "Correlogram: no distance class is significantly more similar than average after the progressive correction.")
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
cs_publish(list(
method = "multivariate.mantel",
methodVersion = "1.0.1",
title = if (!is.null(C)) "Partial Mantel test" else "Mantel test",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("%s test, r_M = %.2f, %s", kind, r, cs_fmt_p(p)),
statistics = list(list(key = "r", label = "r_M", value = r), list(key = "p", label = "p", value = p, format = "p"),
list(key = "pairs", label = "Pairs", value = res$pairs)),
tables = tables,
effectSizes = list(list(key = "r", label = "Mantel r", value = r, method = "Correlation of the pairwise dissimilarities")),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("%sMantel r over %d pairs of rows; ", if (!is.null(C)) "Partial " else "", as.integer(res$pairs)),
if (!is.null(C)) "the third set is standardized Euclidean distance; " else "",
sprintf("%s p from %d row permutations of the first matrix (seed %d).", sub("_", "-", alternative), n_perm, as.integer(seed)),
if (!is.null(cg)) " Correlogram classes split the second matrix's range into equal widths; p-values are two-sided with a progressive Bonferroni correction (Legendre & Legendre 2012)." else "")),
values = values,
charts = charts
))
Mantel test, r_M = 0.30, p = .005
- r_M
- 0.3047
- p
- .005
- Pairs
- 276
Effect size
- Mantel r 0.3047
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Linear relation between the dissimilarities — The Mantel r measures a linear (Pearson) or monotone (Spearman) relation between pairwise dissimilarities, not between the raw variables.
- Exchangeable objects — Rows are permuted as whole objects; with spatial or temporal structure in both matrices the permutation p is too small (Legendre, Fortin & Borcard 2015).
Upper quantiles of the permutation distribution
| Quantile | r_M |
|---|---|
| 90% | 0.1054 |
| 95% | 0.1362 |
| 97.5% | 0.1500 |
| 99% | 0.1800 |
- Mantel r over 276 pairs of rows; greater p from 199 row permutations of the first matrix (seed 42).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Mantel test (and partial Mantel, correlogram)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.mantel 1.0.1 · spec adb6f94682fb279f
# Dataset: mv_vare (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 mvdist
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mv_vare.parquet", columns=["Callvulg", "Empenigr", "Rhodtome", "Vaccmyrt", "Vaccviti", "Pinusylv", "Descflex", "Betupube", "Vacculig", "Diphcomp", "Dicrsp", "Dicrfusc", "Dicrpoly", "Hylosple", "Pleuschr", "Polypili", "Polyjuni", "Polycomm", "Pohlnuta", "Ptilcili", "Barbhatc", "Cladarbu", "Cladrang", "Cladstel", "Cladunci", "Cladcocc", "Cladcorn", "Cladgrac", "Cladfimb", "Cladcris", "Cladchlo", "Cladbotr", "Cladamau", "Cladsp", "Cetreric", "Cetrisla", "Flavniva", "Nepharct", "Stersp", "Peltapht", "Icmaeric", "Cladcerv", "Claddefo", "Cladphyl", "N", "P", "K", "Ca", "Mg", "S", "Al", "Fe", "Mn", "Zn", "Mo", "Baresoil", "Humdepth", "pH"])
n_input = len(df)
df = df.dropna(subset=["Callvulg", "Empenigr", "Rhodtome", "Vaccmyrt", "Vaccviti", "Pinusylv", "Descflex", "Betupube", "Vacculig", "Diphcomp", "Dicrsp", "Dicrfusc", "Dicrpoly", "Hylosple", "Pleuschr", "Polypili", "Polyjuni", "Polycomm", "Pohlnuta", "Ptilcili", "Barbhatc", "Cladarbu", "Cladrang", "Cladstel", "Cladunci", "Cladcocc", "Cladcorn", "Cladgrac", "Cladfimb", "Cladcris", "Cladchlo", "Cladbotr", "Cladamau", "Cladsp", "Cetreric", "Cetrisla", "Flavniva", "Nepharct", "Stersp", "Peltapht", "Icmaeric", "Cladcerv", "Claddefo", "Cladphyl", "N", "P", "K", "Ca", "Mg", "S", "Al", "Fe", "Mn", "Zn", "Mo", "Baresoil", "Humdepth", "pH"]) # listwise deletion over the analysis columns
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, ["Callvulg", "Empenigr", "Rhodtome", "Vaccmyrt", "Vaccviti", "Pinusylv", "Descflex", "Betupube", "Vacculig", "Diphcomp", "Dicrsp", "Dicrfusc", "Dicrpoly", "Hylosple", "Pleuschr", "Polypili", "Polyjuni", "Polycomm", "Pohlnuta", "Ptilcili", "Barbhatc", "Cladarbu", "Cladrang", "Cladstel", "Cladunci", "Cladcocc", "Cladcorn", "Cladgrac", "Cladfimb", "Cladcris", "Cladchlo", "Cladbotr", "Cladamau", "Cladsp", "Cetreric", "Cetrisla", "Flavniva", "Nepharct", "Stersp", "Peltapht", "Icmaeric", "Cladcerv", "Claddefo", "Cladphyl", "N", "P", "K", "Ca", "Mg", "S", "Al", "Fe", "Mn", "Zn", "Mo", "Baresoil", "Humdepth", "pH"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
# Mantel test (Mantel 1967): correlation between the dissimilarities of two sets of variables measured on
# the same rows, p by permuting the rows (and columns) of the first matrix together. A third set gives the
# partial Mantel test (Smouse, Long & Sokal 1986); the correlogram tests distance classes of the second.
x_vars = ["Callvulg", "Empenigr", "Rhodtome", "Vaccmyrt", "Vaccviti", "Pinusylv", "Descflex", "Betupube", "Vacculig", "Diphcomp", "Dicrsp", "Dicrfusc", "Dicrpoly", "Hylosple", "Pleuschr", "Polypili", "Polyjuni", "Polycomm", "Pohlnuta", "Ptilcili", "Barbhatc", "Cladarbu", "Cladrang", "Cladstel", "Cladunci", "Cladcocc", "Cladcorn", "Cladgrac", "Cladfimb", "Cladcris", "Cladchlo", "Cladbotr", "Cladamau", "Cladsp", "Cetreric", "Cetrisla", "Flavniva", "Nepharct", "Stersp", "Peltapht", "Icmaeric", "Cladcerv", "Claddefo", "Cladphyl"]
y_vars = ["N", "P", "K", "Ca", "Mg", "S", "Al", "Fe", "Mn", "Zn", "Mo", "Baresoil", "Humdepth", "pH"]
z_vars = []
x_metric = "bray"
y_metric = "euclidean"
x_transform = "none"
y_transform = "standardize"
method = "pearson" # pearson | spearman
alternative = "greater" # greater | two_sided | less
correlogram = False
n_classes = int(0)
seed = 42
n_perm = int(199)
alpha = 0.05
DIST_LABEL = {"euclidean": "Euclidean", "manhattan": "Manhattan", "bray": "Bray–Curtis", "jaccard": "Jaccard", "gower": "Gower"}
n = len(df)
if n > 3000:
raise ValueError(f"The Mantel test uses n × n matrices; {n} rows is too many (at most 3000).")
if n < 5:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="The Mantel test", min=5, n=n)
A = mvdist.distance(mvdist.transform(df[x_vars].to_numpy(dtype=float), x_transform), x_metric)
B = mvdist.distance(mvdist.transform(df[y_vars].to_numpy(dtype=float), y_transform), y_metric)
C = mvdist.distance(mvdist.transform(df[z_vars].to_numpy(dtype=float), "standardize"), "euclidean") if z_vars else None
res = mvdist.mantel(A, B, C, method, alternative, n_perm, seed)
r, p = res["r"], res["p"]
cg = mvdist.correlogram(A, B, n_classes, method, n_perm, seed) if correlogram else None
# %% Assumptions
assumptions = [
{"key": "linear", "label": "Linear relation between the dissimilarities", "status": "info",
"detail": "The Mantel r measures a linear (Pearson) or monotone (Spearman) relation between pairwise dissimilarities, not between the raw variables."},
{"key": "exchangeable", "label": "Exchangeable objects", "status": "info",
"detail": "Rows are permuted as whole objects; with spatial or temporal structure in both matrices the permutation p is too small (Legendre, Fortin & Borcard 2015)."},
]
# %% Result
kind = "partial Mantel" if C is not None else "Mantel"
xs, ys = ", ".join(x_vars), ", ".join(y_vars)
cond = f", controlling for {', '.join(z_vars)}" if C is not None else ""
sig = p < alpha
direction = "positively" if r > 0 else "negatively"
summary = (f"The {kind} test ({'Spearman' if method == 'spearman' else 'Pearson'}) between the {DIST_LABEL[x_metric]} dissimilarities of {xs} "
f"and the {DIST_LABEL[y_metric]} dissimilarities of {ys}{cond}: r_M = {r:.3f}, {cs.fmt_p(p)} ({n_perm} permutations) — "
+ (f"pairs of rows that differ more in one set differ {'more' if r > 0 else 'less'} in the other." if sig
else "no evidence that the two sets of dissimilarities are related."))
values = {"r": r, "p": p, "n": n, "pairs": res["pairs"], "n_perm": n_perm, "partial": C is not None,
"q90": float(res["quantiles"][0]), "q95": float(res["quantiles"][1]), "q975": float(res["quantiles"][2]), "q99": float(res["quantiles"][3])}
tables = [{"key": "null", "title": "Upper quantiles of the permutation distribution",
"columns": [{"key": "q", "label": "Quantile", "type": "string"}, {"key": "value", "label": "r_M", "type": "number"}],
"rows": [{"q": q, "value": float(v)} for q, v in zip(["90%", "95%", "97.5%", "99%"], res["quantiles"])]}]
charts = []
I, J = mvdist.pairs(n)
pick = np.unique(np.round(np.linspace(0, I.size - 1, min(I.size, 5000))).astype(int))
charts.append(cs.chart("pairs", "distance-distance", "Dissimilarity pairs", {
"x": cs.col(f"{DIST_LABEL[y_metric]} dissimilarity of {ys}", B[I[pick], J[pick]]),
"y": cs.col(f"{DIST_LABEL[x_metric]} dissimilarity of {xs}", A[I[pick], J[pick]])}, controls={"line": True}))
if cg is not None:
rows = cg["classes"]
for row in rows:
values[f"class_r[{row['class']}]"] = row["r"]
values[f"class_p[{row['class']}]"] = row["p_adj"]
tables.append({"key": "correlogram", "title": f"Mantel correlogram over {cg['n_classes']} distance classes of {ys}",
"columns": [{"key": "class", "label": "Class", "type": "integer"}, {"key": "from", "label": "From", "type": "number"},
{"key": "to", "label": "To", "type": "number"}, {"key": "pairs", "label": "Pairs", "type": "integer"},
{"key": "r", "label": "r_M", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "p_adj", "label": "Progressive p", "type": "pvalue"}],
"rows": [{k_: row[k_] for k_ in ("class", "from", "to", "pairs", "r", "p", "p_adj")} for row in rows]})
ok = [row for row in rows if not np.isnan(row["r"])]
charts.append(cs.chart("correlogram", "mantel-correlogram", f"Mantel correlogram: similarity of {xs} by distance class of {ys}", {
"mid": cs.col(f"Distance class of {ys}", np.array([row["mid"] for row in ok])),
"r": cs.col("Mantel r", np.array([row["r"] for row in ok])),
"p": cs.col("Progressive p", np.array([row["p_adj"] for row in ok])),
"pairs": cs.col("Pairs", np.array([row["pairs"] for row in ok], dtype=float))}, controls={"alpha": alpha}))
first_pos = next((row for row in rows if not np.isnan(row["r"]) and row["r"] > 0 and row["p_adj"] < alpha), None)
summary += (f" Correlogram: rows within the first significant class ({first_pos['from']:.3g}–{first_pos['to']:.3g}) are more similar than average."
if first_pos else " Correlogram: no distance class is significantly more similar than average after the progressive correction.")
values["missing_share"] = n_dropped / n_input if n_input else 0.0
cs.publish({
"method": "multivariate.mantel",
"methodVersion": "1.0.1",
"title": "Partial Mantel test" if C is not None else "Mantel test",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{kind} test, r_M = {r:.2f}, {cs.fmt_p(p)}",
"statistics": [{"key": "r", "label": "r_M", "value": r}, {"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "pairs", "label": "Pairs", "value": res["pairs"]}],
"tables": tables,
"effectSizes": [{"key": "r", "label": "Mantel r", "value": r, "method": "Correlation of the pairwise dissimilarities"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"{'Partial ' if C is not None else ''}Mantel r over {res['pairs']} pairs of rows; "
+ ("the third set is standardized Euclidean distance; " if C is not None else "")
+ f"{alternative.replace('_', '-')} p from {n_perm} row permutations of the first matrix (seed {seed})."
+ (" Correlogram classes split the second matrix's range into equal widths; p-values are two-sided with a progressive Bonferroni correction (Legendre & Legendre 2012)." if cg is not None else "")],
"values": values,
"charts": charts,
})
Plants with Bray–Curtis, chemistry with standardized Euclidean: = 0.30, p = 0.005 with 199 permutations.
The permutation distribution's 95th percentile is 0.14, so that observed sits well above it.
Now look at the Dissimilarity pairs chart. Is the relation straight? Do a few pastures drive it?
Small r, big plot
ReflectMantel r values look small next to ordinary correlations, even for strong relations. You can't read them on the usual scale for correlations, because they relate pairwise distances, not values.
Unrelated random tables behave as they should: on simulated data, = −0.06, p = 0.72.
If someone reported a Mantel r to you as an effect size, what would you ask them to show alongside it?
Partial Mantel, and a warning
PredictPredict first
Soil and plants may both depend on a third factor: aluminum and iron. A partial Mantel test controls for a third matrix.
With metals as Control set, Spearman falls to 0.17, p = 0.05. Can you treat this as proof that the confounder is dealt with?
Reveal
Not reliably. Partial Mantel tests can reject too often when the data have spatial structure (Guillot & Rousset, 2013). Treat the drop as descriptive, and use constrained ordination or spatial regression for firmer answers.
Mantel correlograms
ReadInstead of one r over all distances, a correlogram computes one per distance class. On the oribatid mites, the shortest distance classes have a positive r, and the longer ones don't.
Mantel test, r_M = 0.38, p = .010
- r_M
- 0.3845
- p
- .010
- Pairs
- 2,415
Effect size
- Mantel r 0.3845
Assumptions
- Linear relation between the dissimilarities — The Mantel r measures a linear (Pearson) or monotone (Spearman) relation between pairwise dissimilarities, not between the raw variables.
- Exchangeable objects — Rows are permuted as whole objects; with spatial or temporal structure in both matrices the permutation p is too small (Legendre, Fortin & Borcard 2015).
Upper quantiles of the permutation distribution
| Quantile | r_M |
|---|---|
| 90% | 0.0291 |
| 95% | 0.0649 |
| 97.5% | 0.0723 |
| 99% | 0.0762 |
Mantel correlogram over 13 distance classes of x, y
| Class | From | To | Pairs | r_M | p | Progressive p |
|---|---|---|---|---|---|---|
| 1 | 0.1500 | 0.8784 | 179 | 0.2037 | .010 | .010 |
| 2 | 0.8784 | 1.607 | 325 | 0.2251 | .010 | .020 |
| 3 | 1.607 | 2.335 | 398 | 0.1716 | .010 | .030 |
| 4 | 2.335 | 3.063 | 348 | 0.0312 | .190 | .760 |
| 5 | 3.063 | 3.792 | 250 | −0.0638 | .010 | .760 |
| 6 | 3.792 | 4.520 | 234 | −0.1581 | .010 | .760 |
| 7 | 4.520 | 5.249 | 182 | −0.1713 | .010 | .760 |
| 8 | 5.249 | 5.977 | 163 | −0.1477 | .010 | .760 |
| 9 | 5.977 | 6.705 | 130 | −0.1377 | .010 | .760 |
| 10 | 6.705 | 7.434 | 92 | −0.0980 | .010 | .760 |
| 11 | 7.434 | 8.162 | 65 | −0.0338 | .210 | 1.000 |
| 12 | 8.162 | 8.890 | 33 | −0.0206 | .320 | 1.000 |
| 13 | 8.890 | 9.619 | 16 | 0.0167 | .520 | 1.000 |
- Mantel r over 2415 pairs of rows; greater p from 99 row permutations of the first matrix (seed 42). Correlogram classes split the second matrix's range into equal widths; p-values are two-sided with a progressive Bonferroni correction (Legendre & Legendre 2012).
The exact R script · R R version 4.5.1 (2025-06-13)
# Mantel test (and partial Mantel, correlogram)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.mantel 1.0.1 · spec ab5ac79c96e0ade3
# Dataset: mv_mite (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/mv_mite.parquet", col_select = c("Brachy", "PHTH", "HPAV", "RARD", "SSTR", "Protopl", "MEGR", "MPRO", "TVIE", "HMIN", "HMIN2", "NPRA", "TVEL", "ONOV", "SUCT", "LCIL", "x", "y")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Brachy", "PHTH", "HPAV", "RARD", "SSTR", "Protopl", "MEGR", "MPRO", "TVIE", "HMIN", "HMIN2", "NPRA", "TVEL", "ONOV", "SUCT", "LCIL", "x", "y")]), , 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("Brachy", "PHTH", "HPAV", "RARD", "SSTR", "Protopl", "MEGR", "MPRO", "TVIE", "HMIN", "HMIN2", "NPRA", "TVEL", "ONOV", "SUCT", "LCIL", "x", "y")) # infinite values stop the run (registry/errors.yaml)
# %% Test
# Mantel test (Mantel 1967): correlation between the dissimilarities of two sets of variables measured on
# the same rows, p by permuting the rows (and columns) of the first matrix together. A third set gives the
# partial Mantel test (Smouse, Long & Sokal 1986); the correlogram tests distance classes of the second.
x_vars <- c("Brachy", "PHTH", "HPAV", "RARD", "SSTR", "Protopl", "MEGR", "MPRO", "TVIE", "HMIN", "HMIN2", "NPRA", "TVEL", "ONOV", "SUCT", "LCIL")
y_vars <- c("x", "y")
z_vars <- character(0)
x_metric <- "euclidean"
y_metric <- "euclidean"
x_transform <- "hellinger"
y_transform <- "none"
method <- "pearson" # pearson | spearman
alternative <- "greater" # greater | two_sided | less
correlogram <- TRUE
n_classes <- as.integer(0)
seed <- 42
n_perm <- as.integer(99)
alpha <- 0.05
DIST_LABEL <- c(euclidean = "Euclidean", manhattan = "Manhattan", bray = "Bray–Curtis", jaccard = "Jaccard", gower = "Gower")
n <- nrow(df)
if (n > 3000) stop(sprintf("The Mantel test uses n × n matrices; %d rows is too many (at most 3000).", n))
if (n < 5) cs_error("CS_E_TOO_FEW_ROWS", what = "The Mantel test", min = 5, n = n)
A <- cs_mvd_distance(cs_mvd_transform(as.matrix(df[x_vars]), x_transform), x_metric)
B <- cs_mvd_distance(cs_mvd_transform(as.matrix(df[y_vars]), y_transform), y_metric)
C <- if (length(z_vars)) cs_mvd_distance(cs_mvd_transform(as.matrix(df[z_vars]), "standardize"), "euclidean") else NULL
res <- cs_mvd_mantel(A, B, C, method, alternative, n_perm, seed)
r <- res$r
p <- res$p
cg <- if (correlogram) cs_mvd_correlogram(A, B, n_classes, method, n_perm, seed) else NULL
# %% Assumptions
assumptions <- list(
list(key = "linear", label = "Linear relation between the dissimilarities", status = "info",
detail = "The Mantel r measures a linear (Pearson) or monotone (Spearman) relation between pairwise dissimilarities, not between the raw variables."),
list(key = "exchangeable", label = "Exchangeable objects", status = "info",
detail = "Rows are permuted as whole objects; with spatial or temporal structure in both matrices the permutation p is too small (Legendre, Fortin & Borcard 2015).")
)
# %% Result
kind <- if (!is.null(C)) "partial Mantel" else "Mantel"
xs <- paste(x_vars, collapse = ", ")
ys <- paste(y_vars, collapse = ", ")
cond <- if (!is.null(C)) paste0(", controlling for ", paste(z_vars, collapse = ", ")) else ""
summary <- paste0(sprintf("The %s test (%s) between the %s dissimilarities of %s and the %s dissimilarities of %s%s: r_M = %.3f, %s (%d permutations) — ",
kind, if (method == "spearman") "Spearman" else "Pearson", DIST_LABEL[[x_metric]], xs, DIST_LABEL[[y_metric]], ys, cond, r, cs_fmt_p(p), n_perm),
if (p < alpha) sprintf("pairs of rows that differ more in one set differ %s in the other.", if (r > 0) "more" else "less")
else "no evidence that the two sets of dissimilarities are related.")
values <- list(r = r, p = p, n = n, pairs = res$pairs, n_perm = n_perm, partial = !is.null(C),
q90 = res$quantiles[1], q95 = res$quantiles[2], q975 = res$quantiles[3], q99 = res$quantiles[4])
tables <- list(list(key = "null", title = "Upper quantiles of the permutation distribution",
columns = list(list(key = "q", label = "Quantile", type = "string"), list(key = "value", label = "r_M", type = "number")),
rows = data.frame(q = c("90%", "95%", "97.5%", "99%"), value = res$quantiles)))
pr <- cs_mvd_pairs(n)
pick <- unique(round(seq(1, length(pr$i), length.out = min(length(pr$i), 5000))))
charts <- list(cs_chart("pairs", "distance-distance", "Dissimilarity pairs", list(
x = cs_col(sprintf("%s dissimilarity of %s", DIST_LABEL[[y_metric]], ys), B[cbind(pr$i[pick], pr$j[pick])]),
y = cs_col(sprintf("%s dissimilarity of %s", DIST_LABEL[[x_metric]], xs), A[cbind(pr$i[pick], pr$j[pick])])), controls = list(line = TRUE)))
if (!is.null(cg)) {
rows <- cg$classes
for (row in rows) {
values[[sprintf("class_r[%d]", as.integer(row$class))]] <- row$r
values[[sprintf("class_p[%d]", as.integer(row$class))]] <- row$p_adj
}
tables[[2]] <- list(key = "correlogram", title = sprintf("Mantel correlogram over %d distance classes of %s", as.integer(cg$n_classes), ys),
columns = list(list(key = "class", label = "Class", type = "integer"), list(key = "from", label = "From", type = "number"),
list(key = "to", label = "To", type = "number"), list(key = "pairs", label = "Pairs", type = "integer"),
list(key = "r", label = "r_M", type = "number"), list(key = "p", label = "p", type = "pvalue"),
list(key = "p_adj", label = "Progressive p", type = "pvalue")),
rows = lapply(rows, function(row) row[c("class", "from", "to", "pairs", "r", "p", "p_adj")]))
ok <- Filter(function(row) !is.nan(row$r), rows)
charts[[2]] <- cs_chart("correlogram", "mantel-correlogram", sprintf("Mantel correlogram: similarity of %s by distance class of %s", xs, ys), list(
mid = cs_col(sprintf("Distance class of %s", ys), vapply(ok, `[[`, 0, "mid")),
r = cs_col("Mantel r", vapply(ok, `[[`, 0, "r")),
p = cs_col("Progressive p", vapply(ok, `[[`, 0, "p_adj")),
pairs = cs_col("Pairs", as.numeric(vapply(ok, `[[`, 0, "pairs")))), controls = list(alpha = alpha))
first_pos <- Find(function(row) !is.nan(row$r) && row$r > 0 && row$p_adj < alpha, rows)
summary <- paste(summary, if (!is.null(first_pos))
sprintf("Correlogram: rows within the first significant class (%s–%s) are more similar than average.", format(signif(first_pos$from, 3)), format(signif(first_pos$to, 3)))
else "Correlogram: no distance class is significantly more similar than average after the progressive correction.")
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
cs_publish(list(
method = "multivariate.mantel",
methodVersion = "1.0.1",
title = if (!is.null(C)) "Partial Mantel test" else "Mantel test",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("%s test, r_M = %.2f, %s", kind, r, cs_fmt_p(p)),
statistics = list(list(key = "r", label = "r_M", value = r), list(key = "p", label = "p", value = p, format = "p"),
list(key = "pairs", label = "Pairs", value = res$pairs)),
tables = tables,
effectSizes = list(list(key = "r", label = "Mantel r", value = r, method = "Correlation of the pairwise dissimilarities")),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("%sMantel r over %d pairs of rows; ", if (!is.null(C)) "Partial " else "", as.integer(res$pairs)),
if (!is.null(C)) "the third set is standardized Euclidean distance; " else "",
sprintf("%s p from %d row permutations of the first matrix (seed %d).", sub("_", "-", alternative), n_perm, as.integer(seed)),
if (!is.null(cg)) " Correlogram classes split the second matrix's range into equal widths; p-values are two-sided with a progressive Bonferroni correction (Legendre & Legendre 2012)." else "")),
values = values,
charts = charts
))
Mantel test, r_M = 0.38, p = .010
- r_M
- 0.3845
- p
- .010
- Pairs
- 2,415
Effect size
- Mantel r 0.3845
Assumptions
- Linear relation between the dissimilarities — The Mantel r measures a linear (Pearson) or monotone (Spearman) relation between pairwise dissimilarities, not between the raw variables.
- Exchangeable objects — Rows are permuted as whole objects; with spatial or temporal structure in both matrices the permutation p is too small (Legendre, Fortin & Borcard 2015).
Upper quantiles of the permutation distribution
| Quantile | r_M |
|---|---|
| 90% | 0.0291 |
| 95% | 0.0649 |
| 97.5% | 0.0723 |
| 99% | 0.0762 |
Mantel correlogram over 13 distance classes of x, y
| Class | From | To | Pairs | r_M | p | Progressive p |
|---|---|---|---|---|---|---|
| 1 | 0.1500 | 0.8784 | 179 | 0.2037 | .010 | .010 |
| 2 | 0.8784 | 1.607 | 325 | 0.2251 | .010 | .020 |
| 3 | 1.607 | 2.335 | 398 | 0.1716 | .010 | .030 |
| 4 | 2.335 | 3.063 | 348 | 0.0312 | .190 | .760 |
| 5 | 3.063 | 3.792 | 250 | −0.0638 | .010 | .760 |
| 6 | 3.792 | 4.520 | 234 | −0.1581 | .010 | .760 |
| 7 | 4.520 | 5.249 | 182 | −0.1713 | .010 | .760 |
| 8 | 5.249 | 5.977 | 163 | −0.1477 | .010 | .760 |
| 9 | 5.977 | 6.705 | 130 | −0.1377 | .010 | .760 |
| 10 | 6.705 | 7.434 | 92 | −0.0980 | .010 | .760 |
| 11 | 7.434 | 8.162 | 65 | −0.0338 | .210 | 1.000 |
| 12 | 8.162 | 8.890 | 33 | −0.0206 | .320 | 1.000 |
| 13 | 8.890 | 9.619 | 16 | 0.0167 | .520 | 1.000 |
- Mantel r over 2415 pairs of rows; greater p from 99 row permutations of the first matrix (seed 42). Correlogram classes split the second matrix's range into equal widths; p-values are two-sided with a progressive Bonferroni correction (Legendre & Legendre 2012).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Mantel test (and partial Mantel, correlogram)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.mantel 1.0.1 · spec ab5ac79c96e0ade3
# Dataset: mv_mite (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 mvdist
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mv_mite.parquet", columns=["Brachy", "PHTH", "HPAV", "RARD", "SSTR", "Protopl", "MEGR", "MPRO", "TVIE", "HMIN", "HMIN2", "NPRA", "TVEL", "ONOV", "SUCT", "LCIL", "x", "y"])
n_input = len(df)
df = df.dropna(subset=["Brachy", "PHTH", "HPAV", "RARD", "SSTR", "Protopl", "MEGR", "MPRO", "TVIE", "HMIN", "HMIN2", "NPRA", "TVEL", "ONOV", "SUCT", "LCIL", "x", "y"]) # listwise deletion over the analysis columns
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, ["Brachy", "PHTH", "HPAV", "RARD", "SSTR", "Protopl", "MEGR", "MPRO", "TVIE", "HMIN", "HMIN2", "NPRA", "TVEL", "ONOV", "SUCT", "LCIL", "x", "y"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
# Mantel test (Mantel 1967): correlation between the dissimilarities of two sets of variables measured on
# the same rows, p by permuting the rows (and columns) of the first matrix together. A third set gives the
# partial Mantel test (Smouse, Long & Sokal 1986); the correlogram tests distance classes of the second.
x_vars = ["Brachy", "PHTH", "HPAV", "RARD", "SSTR", "Protopl", "MEGR", "MPRO", "TVIE", "HMIN", "HMIN2", "NPRA", "TVEL", "ONOV", "SUCT", "LCIL"]
y_vars = ["x", "y"]
z_vars = []
x_metric = "euclidean"
y_metric = "euclidean"
x_transform = "hellinger"
y_transform = "none"
method = "pearson" # pearson | spearman
alternative = "greater" # greater | two_sided | less
correlogram = True
n_classes = int(0)
seed = 42
n_perm = int(99)
alpha = 0.05
DIST_LABEL = {"euclidean": "Euclidean", "manhattan": "Manhattan", "bray": "Bray–Curtis", "jaccard": "Jaccard", "gower": "Gower"}
n = len(df)
if n > 3000:
raise ValueError(f"The Mantel test uses n × n matrices; {n} rows is too many (at most 3000).")
if n < 5:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="The Mantel test", min=5, n=n)
A = mvdist.distance(mvdist.transform(df[x_vars].to_numpy(dtype=float), x_transform), x_metric)
B = mvdist.distance(mvdist.transform(df[y_vars].to_numpy(dtype=float), y_transform), y_metric)
C = mvdist.distance(mvdist.transform(df[z_vars].to_numpy(dtype=float), "standardize"), "euclidean") if z_vars else None
res = mvdist.mantel(A, B, C, method, alternative, n_perm, seed)
r, p = res["r"], res["p"]
cg = mvdist.correlogram(A, B, n_classes, method, n_perm, seed) if correlogram else None
# %% Assumptions
assumptions = [
{"key": "linear", "label": "Linear relation between the dissimilarities", "status": "info",
"detail": "The Mantel r measures a linear (Pearson) or monotone (Spearman) relation between pairwise dissimilarities, not between the raw variables."},
{"key": "exchangeable", "label": "Exchangeable objects", "status": "info",
"detail": "Rows are permuted as whole objects; with spatial or temporal structure in both matrices the permutation p is too small (Legendre, Fortin & Borcard 2015)."},
]
# %% Result
kind = "partial Mantel" if C is not None else "Mantel"
xs, ys = ", ".join(x_vars), ", ".join(y_vars)
cond = f", controlling for {', '.join(z_vars)}" if C is not None else ""
sig = p < alpha
direction = "positively" if r > 0 else "negatively"
summary = (f"The {kind} test ({'Spearman' if method == 'spearman' else 'Pearson'}) between the {DIST_LABEL[x_metric]} dissimilarities of {xs} "
f"and the {DIST_LABEL[y_metric]} dissimilarities of {ys}{cond}: r_M = {r:.3f}, {cs.fmt_p(p)} ({n_perm} permutations) — "
+ (f"pairs of rows that differ more in one set differ {'more' if r > 0 else 'less'} in the other." if sig
else "no evidence that the two sets of dissimilarities are related."))
values = {"r": r, "p": p, "n": n, "pairs": res["pairs"], "n_perm": n_perm, "partial": C is not None,
"q90": float(res["quantiles"][0]), "q95": float(res["quantiles"][1]), "q975": float(res["quantiles"][2]), "q99": float(res["quantiles"][3])}
tables = [{"key": "null", "title": "Upper quantiles of the permutation distribution",
"columns": [{"key": "q", "label": "Quantile", "type": "string"}, {"key": "value", "label": "r_M", "type": "number"}],
"rows": [{"q": q, "value": float(v)} for q, v in zip(["90%", "95%", "97.5%", "99%"], res["quantiles"])]}]
charts = []
I, J = mvdist.pairs(n)
pick = np.unique(np.round(np.linspace(0, I.size - 1, min(I.size, 5000))).astype(int))
charts.append(cs.chart("pairs", "distance-distance", "Dissimilarity pairs", {
"x": cs.col(f"{DIST_LABEL[y_metric]} dissimilarity of {ys}", B[I[pick], J[pick]]),
"y": cs.col(f"{DIST_LABEL[x_metric]} dissimilarity of {xs}", A[I[pick], J[pick]])}, controls={"line": True}))
if cg is not None:
rows = cg["classes"]
for row in rows:
values[f"class_r[{row['class']}]"] = row["r"]
values[f"class_p[{row['class']}]"] = row["p_adj"]
tables.append({"key": "correlogram", "title": f"Mantel correlogram over {cg['n_classes']} distance classes of {ys}",
"columns": [{"key": "class", "label": "Class", "type": "integer"}, {"key": "from", "label": "From", "type": "number"},
{"key": "to", "label": "To", "type": "number"}, {"key": "pairs", "label": "Pairs", "type": "integer"},
{"key": "r", "label": "r_M", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "p_adj", "label": "Progressive p", "type": "pvalue"}],
"rows": [{k_: row[k_] for k_ in ("class", "from", "to", "pairs", "r", "p", "p_adj")} for row in rows]})
ok = [row for row in rows if not np.isnan(row["r"])]
charts.append(cs.chart("correlogram", "mantel-correlogram", f"Mantel correlogram: similarity of {xs} by distance class of {ys}", {
"mid": cs.col(f"Distance class of {ys}", np.array([row["mid"] for row in ok])),
"r": cs.col("Mantel r", np.array([row["r"] for row in ok])),
"p": cs.col("Progressive p", np.array([row["p_adj"] for row in ok])),
"pairs": cs.col("Pairs", np.array([row["pairs"] for row in ok], dtype=float))}, controls={"alpha": alpha}))
first_pos = next((row for row in rows if not np.isnan(row["r"]) and row["r"] > 0 and row["p_adj"] < alpha), None)
summary += (f" Correlogram: rows within the first significant class ({first_pos['from']:.3g}–{first_pos['to']:.3g}) are more similar than average."
if first_pos else " Correlogram: no distance class is significantly more similar than average after the progressive correction.")
values["missing_share"] = n_dropped / n_input if n_input else 0.0
cs.publish({
"method": "multivariate.mantel",
"methodVersion": "1.0.1",
"title": "Partial Mantel test" if C is not None else "Mantel test",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{kind} test, r_M = {r:.2f}, {cs.fmt_p(p)}",
"statistics": [{"key": "r", "label": "r_M", "value": r}, {"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "pairs", "label": "Pairs", "value": res["pairs"]}],
"tables": tables,
"effectSizes": [{"key": "r", "label": "Mantel r", "value": r, "method": "Correlation of the pairwise dissimilarities"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"{'Partial ' if C is not None else ''}Mantel r over {res['pairs']} pairs of rows; "
+ ("the third set is standardized Euclidean distance; " if C is not None else "")
+ f"{alternative.replace('_', '-')} p from {n_perm} row permutations of the first matrix (seed {seed})."
+ (" Correlogram classes split the second matrix's range into equal widths; p-values are two-sided with a progressive Bonferroni correction (Legendre & Legendre 2012)." if cg is not None else "")],
"values": values,
"charts": charts,
})
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 chart(s) dropped to stay under 100 KB.
The overall here is 0.38. Class p-values are adjusted in sequence, and they rest on few pairs at the longest distances.
Check your understanding
CheckpointCheck yourself
You have 20 sites. How many distinct pairs enter a Mantel correlation?
Show the answer
Answer: 190
.
Check yourself
Why does the Mantel test permute whole rows of one table rather than individual dissimilarities?
Show the answer
Answer: b
Permuting sites keeps each matrix's internal dependence intact, so the null reflects the actual structure of the data.
Check yourself
= 0.30, p = 0.005. Which statement can you defend?
Show the answer
Answer: c
It relates distances to distances. It says nothing about causation, and isn't the share of plant variance explained.
Do it in CodeSplash
In the appFill First set and Second set, and optionally Control set. Each has its own dissimilarity and transform. Turn on Mantel correlogram to bin by distance.
import pandas as pd
from scipy.spatial.distance import pdist, squareform
from sklearn.preprocessing import scale
from skbio.stats.distance import DistanceMatrix, mantel
plants = pd.read_csv("varespec.csv")
chem = pd.read_csv("varechem.csv")
A = DistanceMatrix(squareform(pdist(plants.to_numpy(), "braycurtis")))
B = DistanceMatrix(squareform(pdist(scale(chem.to_numpy()), "euclidean")))
print(mantel(A, B, permutations=999))# install.packages("vegan")
library(vegan)
data(varespec); data(varechem)
mantel(vegdist(varespec, "bray"), dist(scale(varechem)), permutations = 999)Recap
Recap- The Mantel test correlates two dissimilarity matrices and shuffles rows, because pairs aren't independent.
- It speaks about distances. Don't square into "variance explained".
- Plot the pairs, and watch for a few sites driving the result.
- Partial Mantel tests and correlograms are descriptive aids, with known false-positive risks.
Concepts in this lesson