svgmantel-correlogram
Mantel correlogram
Over what distances are rows more alike (or less alike) than average?
How to read it
- Read x as distance classes, y as Mantel r in each class.
- Filled points are significant.
- Positive at short distances and falling suggests rows close together are alike.
- Callout 1: At short distances: rows are alike.
- Callout 2: No association here.
- Callout 3: Hollow: not significant.
Watch out
- Each class is one test: use the corrected p-values shown.
Defaults
- Significance level
- 0.05
- The α below which a point counts as significant.
- Range 0.001 to 0.2, step 0.005
Pinned in the code
- For each distance class the model matrix is 0 for pairs in the class and 1 otherwise, so r > 0 means pairs that close together are more similar than average (positive autocorrelation).
- Filled points are significant at α after the progressive Bonferroni correction (class c's p times c, kept monotone), reading from the shortest distances outwards.
- Classes beyond about half the largest distance contain few, edge-biased pairs; read them with care (Legendre & Legendre 2012).
# Mantel correlogram — Codesplash Chart Lab (recipe "mantel-correlogram")
# controls: alpha=0.05
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("mantel-correlogram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
MID = "distance class (m)"
R = "Mantel r"
P = "progressive p"
PAIRS = "pairs"
ALPHA = 0.05 # filled points: corrected p below α
d = df.dropna(subset=[MID, R]).sort_values(MID)
sig = (d[P] < ALPHA).to_numpy() if P else np.zeros(len(d), bool)
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.axhline(0, color=GREY, linestyle="--", linewidth=1)
ax.plot(d[MID], d[R], color=PALETTE[0], linewidth=1.6)
ax.scatter(d[MID][sig], d[R][sig], s=40, color=PALETTE[0], zorder=3, label=f"significant (p < {ALPHA:g})")
ax.scatter(d[MID][~sig], d[R][~sig], s=40, facecolors="white", edgecolors=REF, zorder=3, label="not significant")
if PAIRS: # how many pairs each class holds (few pairs: read with care)
for xv, yv, nv in zip(d[MID], d[R], d[PAIRS]):
ax.annotate(f"{nv:.0f}", (xv, yv), xytext=(0, 7), textcoords="offset points", ha="center", fontsize=7, color=REF)
lim = max(0.05, d[R].abs().max()) * 1.15
ax.set_ylim(-lim, lim)
ax.set_xlabel(MID)
ax.set_ylabel("Mantel r")
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads mantel-correlogram-demo.csv · app theme from the optional codesplash helper
# Mantel correlogram — Codesplash Chart Lab (recipe "mantel-correlogram")
# controls: alpha=0.05
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("mantel-correlogram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
MID = "distance class (m)"
R = "Mantel r"
P = "progressive p"
PAIRS = "pairs"
ALPHA = 0.05
d = df.dropna(subset=[MID, R]).sort_values(MID)
sig = (d[P] < ALPHA).to_numpy() if P else np.zeros(len(d), bool)
fig = go.Figure(go.Scatter(x=d[MID], y=d[R], mode="lines+markers", name="Mantel r", line=dict(color=PALETTE[0], width=1.6),
marker=dict(size=9, color=[PALETTE[0] if s else "white" for s in sig], line=dict(color=[PALETTE[0] if s else REF for s in sig], width=1.5))))
if PAIRS: # pair counts in the hover
fig.update_traces(customdata=d[PAIRS], hovertemplate="class %{x}<br>r = %{y:.3f}<br>%{customdata:.0f} pairs<extra></extra>")
fig.add_hline(y=0, line=dict(color=GREY, dash="dash"))
fig.update_layout(xaxis_title=MID, yaxis_title="Mantel r", title=f"Filled: corrected p < {ALPHA:g}")
fig.show()Needs pandas, numpy, plotly · reads mantel-correlogram-demo.csv · app theme from the optional codesplash helper
# Mantel correlogram — Codesplash Chart Lab (recipe "mantel-correlogram")
# controls: alpha=0.05
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("mantel-correlogram-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
mid_col <- "distance class (m)"
r_col <- "Mantel r"
p_col <- "progressive p"
pairs_col <- "pairs"
alpha <- 0.05 # filled points: corrected p below alpha
d <- data.frame(mid = df[[mid_col]], r = df[[r_col]], p = if (is.null(p_col)) NA_real_ else df[[p_col]],
pairs = if (is.null(pairs_col)) NA_real_ else df[[pairs_col]]) # pairs per class (few pairs: read with care)
d <- d[!is.na(d$mid) & !is.na(d$r), ]
d <- d[order(d$mid), ]
d$sig <- !is.na(d$p) & d$p < alpha
lim <- max(0.05, abs(d$r)) * 1.15
p <- ggplot(d, aes(mid, r)) +
geom_hline(yintercept = 0, linetype = "dashed", colour = grey_col) +
geom_line(colour = cs_cat[1], linewidth = 0.8) +
geom_point(aes(fill = sig), shape = 21, size = 2.8, colour = ifelse(d$sig, cs_cat[1], ref_col), stroke = 1) +
scale_fill_manual(values = c(`TRUE` = cs_cat[1], `FALSE` = "white"), labels = c(`TRUE` = sprintf("p < %g", alpha), `FALSE` = "not significant"), name = NULL) +
{ if (!is.null(pairs_col)) geom_text(aes(label = round(pairs)), vjust = -1.1, size = 2.5, colour = ref_col) } +
coord_cartesian(ylim = c(-lim, lim)) +
labs(x = mid_col, y = "Mantel r") + theme_cs
print(p)Needs ggplot2 · reads mantel-correlogram-demo.csv · app theme from the optional codesplashr helper