Skip to content

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.

Advanced ~11 min9 steps

What runs in CodeSplash

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

Read first

01

Two tables, one question

Read

Twenty-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.

rM=cor(dijX, dijY),i<jr_M = \text{cor}\big(d^{X}_{ij},\ d^{Y}_{ij}\big), \quad i < j

Note what this measures: it relates distances to distances, not soil values to plant values.

02

How many pairs are there?

Predict

Predict first

With 24 pastures, how many entries go into that correlation?

Would an ordinary correlation test on them be valid?

24: one per pasture276: all pairs of pastures552: both orders of each pair
Reveal

276 pairs, which is 24×23/224 \times 23 / 2. 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.

03

Read a result

In the app
Mantel testRecorded · Python and R agreeRecorded 2026-11-17 · 11 values compared
R

Mantel test, r_M = 0.30, p = .005

r_M
0.3047
p
.005
Pairs
276

Effect size

  • Mantel r 0.3047

Plots

Dissimilarity pairsDo pairs of rows that differ more in one set of variables also differ more in another (the Mantel test's question)?
View data
Euclidean dissimilarity of N, P, K, Ca, Mg, S, Al, Fe, Mn, Zn, Mo, Baresoil, Humdepth, pHBray–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.0770.5310
6.8810.6681
4.4730.5621
2.5080.3747
3.5800.5095
2.6590.6234
2.2960.5338
4.7120.8418
5.1630.3453
2.2140.5450
3.9300.3879
3.1340.6319
4.9030.3604
5.4950.4956
4.2410.3382
6.1140.5277
6.0560.4694
4.9520.5724
4.2110.6584
2.8590.4688
4.9720.6249
6.5550.4459
2.5410.5561
6.9030.3598
4.6400.4056
3.7250.3652
4.2310.4561
3.3220.3580
2.5230.3977
5.1360.5225
5.1440.6064
2.5090.4804
4.7230.3784
3.4390.3376
4.8520.6717
5.5030.7179
3.5220.6355
5.8750.7579
5.4910.6844
4.2720.8206
3.1530.7761
1.7480.6794
4.1240.7645
6.1590.4716
3.3510.7607
5.4800.4935
5.7140.5020
5.4450.5092
6.2110.5010
7.5790.5908
5.7280.5737
5.5030.7577
6.0520.6534
5.1380.4347
6.8180.3369
8.7660.7931
9.0440.8562
8.3400.7441
9.1140.8382
5.6750.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

Quantiler_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
))
Python

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

Quantiler_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: rMr_M = 0.30, p = 0.005 with 199 permutations.

The permutation distribution's 95th percentile is 0.14, so that observed rMr_M sits well above it.

Now look at the Dissimilarity pairs chart. Is the relation straight? Do a few pastures drive it?

04

Small r, big plot

Reflect

Mantel 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, rMr_M = −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?

05

Partial Mantel, and a warning

Predict

Predict 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 rMr_M falls to 0.17, p = 0.05. Can you treat this as proof that the confounder is dealt with?

Yes: the partial test removes spatial structureNot reliably: it can give too many false positivesOnly with Spearman
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.

06

Mantel correlograms

Read

Instead 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 testRecorded · Python and R agreeRecorded 2026-11-17 · 37 values compared
R

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

Quantiler_M
90%0.0291
95%0.0649
97.5%0.0723
99%0.0762

Mantel correlogram over 13 distance classes of x, y

ClassFromToPairsr_MpProgressive p
10.15000.87841790.2037.010.010
20.87841.6073250.2251.010.020
31.6072.3353980.1716.010.030
42.3353.0633480.0312.190.760
53.0633.792250−0.0638.010.760
63.7924.520234−0.1581.010.760
74.5205.249182−0.1713.010.760
85.2495.977163−0.1477.010.760
95.9776.705130−0.1377.010.760
106.7057.43492−0.0980.010.760
117.4348.16265−0.0338.2101.000
128.1628.89033−0.0206.3201.000
138.8909.619160.0167.5201.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
))
Python

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

Quantiler_M
90%0.0291
95%0.0649
97.5%0.0723
99%0.0762

Mantel correlogram over 13 distance classes of x, y

ClassFromToPairsr_MpProgressive p
10.15000.87841790.2037.010.010
20.87841.6073250.2251.010.020
31.6072.3353980.1716.010.030
42.3353.0633480.0312.190.760
53.0633.792250−0.0638.010.760
63.7924.520234−0.1581.010.760
74.5205.249182−0.1713.010.760
85.2495.977163−0.1477.010.760
95.9776.705130−0.1377.010.760
106.7057.43492−0.0980.010.760
117.4348.16265−0.0338.2101.000
128.1628.89033−0.0206.3201.000
138.8909.619160.0167.5201.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 rMr_M here is 0.38. Class p-values are adjusted in sequence, and they rest on few pairs at the longest distances.

07

Check your understanding

Checkpoint

Check yourself

You have 20 sites. How many distinct pairs enter a Mantel correlation?

Show the answer

Answer: 190

20×19/2=19020 \times 19 / 2 = 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

rMr_M = 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 rM2r_M^2 isn't the share of plant variance explained.

08

Do it in CodeSplash

In the app

Fill First set and Second set, and optionally Control set. Each has its own dissimilarity and transform. Turn on Mantel correlogram to bin by distance.

Python
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))
R
# install.packages("vegan")
library(vegan)
data(varespec); data(varechem)
mantel(vegdist(varespec, "bray"), dist(scale(varechem)), permutations = 999)
09

Recap

Recap
  • The Mantel test correlates two dissimilarity matrices and shuffles rows, because pairs aren't independent.
  • It speaks about distances. Don't square rMr_M 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