svgdistance-distance
Dissimilarity–dissimilarity plot
Do pairs of rows that differ more in one set of variables also differ more in another (the Mantel test's question)?
How to read it
- Read each point as a pair of rows: its distance in one matrix against the other.
- A rising cloud means pairs that differ in one set also differ in the other.
- Read r in the legend, then the Mantel test's p.
- Callout 1: A rising line: distances agree.
- Callout 2: Each point: one pair of rows.
Watch out
- Pairs aren't independent. A usual correlation test is wrong: use the permutation p-value.
Defaults
- Least-squares line
- On
- Add the fitted straight line.
Pinned in the code
- One point per pair of rows (n(n − 1)/2 points); the engines send at most 5000 evenly spaced pairs.
- The line is the least-squares fit of the first matrix's dissimilarity on the second's; its correlation is the (Pearson) Mantel statistic.
- The pairs are not independent, so the line's ordinary standard errors are wrong — the Mantel test's permutation p-value is the valid test.
# Dissimilarity–dissimilarity plot — Codesplash Chart Lab (recipe "distance-distance")
# controls: line=true
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("distance-distance-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")
X = "geographic distance (km)"
Y = "Bray–Curtis dissimilarity"
LINE = True
d = df.dropna(subset=[X, Y])
x, y = d[X].to_numpy(float), d[Y].to_numpy(float)
fig, ax = plt.subplots(figsize=(7, 5))
ax.scatter(x, y, s=8 if len(x) > 2000 else 14, alpha=0.25 if len(x) > 2000 else 0.45, color=PALETTE[0])
if LINE and len(x) > 1:
slope, intercept = np.polyfit(x, y, 1) # least squares; its r is the (Pearson) Mantel statistic
r = np.corrcoef(x, y)[0, 1]
xs = np.array([x.min(), x.max()])
ax.plot(xs, intercept + slope * xs, color=REF, linewidth=2, label=f"least squares, r = {r:.3f}")
ax.legend(fontsize=8)
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.set_title("Every pair of rows")
plt.show()Needs pandas, numpy, matplotlib · reads distance-distance-demo.csv · app theme from the optional codesplash helper
# Dissimilarity–dissimilarity plot — Codesplash Chart Lab (recipe "distance-distance")
# controls: line=true
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("distance-distance-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")
X = "geographic distance (km)"
Y = "Bray–Curtis dissimilarity"
LINE = True
d = df.dropna(subset=[X, Y])
x, y = d[X].to_numpy(float), d[Y].to_numpy(float)
fig = go.Figure(go.Scattergl(x=x, y=y, mode="markers", name="pairs", marker=dict(color=PALETTE[0], size=4 if len(x) > 2000 else 6, opacity=0.35)))
if LINE and len(x) > 1:
slope, intercept = np.polyfit(x, y, 1)
r = np.corrcoef(x, y)[0, 1]
xs = np.array([x.min(), x.max()])
fig.add_scatter(x=xs, y=intercept + slope * xs, mode="lines", name=f"least squares, r = {r:.3f}", line=dict(color=REF, width=2))
fig.update_layout(xaxis_title=X, yaxis_title=Y, title="Every pair of rows")
fig.show()Needs pandas, numpy, plotly · reads distance-distance-demo.csv · app theme from the optional codesplash helper
# Dissimilarity–dissimilarity plot — Codesplash Chart Lab (recipe "distance-distance")
# controls: line=true
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("distance-distance-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
x_col <- "geographic distance (km)"
y_col <- "Bray–Curtis dissimilarity"
show_line <- TRUE
d <- data.frame(x = df[[x_col]], y = df[[y_col]])
d <- d[stats::complete.cases(d), ]
r <- stats::cor(d$x, d$y)
p <- ggplot(d, aes(x, y)) +
geom_point(colour = cs_cat[1], alpha = if (nrow(d) > 2000) 0.25 else 0.45, size = if (nrow(d) > 2000) 0.6 else 1.1) +
{ if (show_line) geom_smooth(method = "lm", formula = y ~ x, se = FALSE, colour = ref_col, linewidth = 0.9) } +
labs(x = x_col, y = y_col, title = "Every pair of rows", subtitle = if (show_line) sprintf("least squares, r = %.3f", r) else NULL) + theme_cs
print(p)Needs ggplot2 · reads distance-distance-demo.csv · app theme from the optional codesplashr helper