svgpcoa-centroids
Principal coordinates by group
Do the groups separate in the dissimilarity space, and do they differ in where they sit or in how spread out they are?
How to read it
- Read points as rows placed so that distances match their dissimilarities.
- Read diamonds as group centres.
- Separated centres suggest different locations; different hull sizes suggest different spreads.
- Callout 1: A group centre.
- Callout 2: Hull: the group's spread.
- Callout 3: How much dissimilarity this axis carries.
Watch out
- PERMANOVA reacts to spread as well as location. Check PERMDISP before you read the separation.
Defaults
- Group centre
- Centroid
- The marker drawn for each group; PERMDISP's default centre is the spatial median.
- Also: Spatial median
- Spokes to the centre
- Off
- Lines from each row to its group's centre — the distances PERMDISP compares.
- Convex hulls
- On
- Outline each group with the smallest shape enclosing its points.
Pinned in the code
- Principal coordinates (classical scaling): the eigenvectors of −½ J D² J scaled by √λ; the axis labels give each axis's share of the positive eigenvalues.
- Axes are drawn with equal units, so distances on the plot are comparable in both directions.
- Centres are computed in the plotted two dimensions for display; the test (PERMDISP) uses all axes, including those of negative eigenvalues for non-Euclidean dissimilarities.
- Two axes show only part of the dissimilarity structure — a test can find a difference the first two axes do not show.
# Principal coordinates by group — Codesplash Chart Lab (recipe "pcoa-centroids")
# controls: center=centroid, spokes=false, hulls=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]
df = pd.read_csv("pcoa-centroids-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["management"] = pd.Categorical(df["management"].astype("string"), categories=["grazed", "mown", "natural"])
_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")
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
def centre(xy, how):
"""Centroid, or the spatial median by Weiszfeld's iterations from the mean (as in the app)."""
y = xy.mean(axis=0)
if how != "median":
return y
for _ in range(1000):
d = np.hypot(*(xy - y).T)
keep = d > 1e-15
if not keep.any():
return y
w = 1 / d[keep]
nxt = (xy[keep] * w[:, None]).sum(axis=0) / w.sum()
if np.hypot(*(nxt - y)) <= 1e-10 * (1 + np.hypot(*y)):
return nxt
y = nxt
return y
X = "PCoA 1 (31.4%)"
Y = "PCoA 2 (17.9%)"
G = "management"
CENTER, SPOKES, HULLS = "centroid", False, True
d = df.dropna(subset=[X, Y] + ([G] if G else []))
groups = levels_of(d[G]) if G else ["All rows"]
fig, ax = plt.subplots(figsize=(7, 6))
for i, k in enumerate(groups):
g = d[d[G].astype(str) == str(k)] if G else d
xy, col = g[[X, Y]].to_numpy(float), PALETTE[i % len(PALETTE)]
ctr = centre(xy, CENTER)
if HULLS and len(xy) >= 3:
try:
h = ConvexHull(xy).vertices
ax.fill(xy[h, 0], xy[h, 1], color=col, alpha=0.07, edgecolor=col, linewidth=1)
except Exception: # collinear points have no hull
pass
if SPOKES:
for px, py in xy:
ax.plot([ctr[0], px], [ctr[1], py], color=col, alpha=0.3, linewidth=0.8)
ax.scatter(xy[:, 0], xy[:, 1], s=14, color=col, marker=SERIES_MARKERS[i % 8], alpha=0.6, label=f"{k} (n = {len(xy)})") # shape per group, as in the app
if G:
ax.scatter([ctr[0]], [ctr[1]], marker="D", s=60, color=col, edgecolors="white", linewidths=1.2, zorder=3)
ax.set_aspect("equal", adjustable="datalim") # equal units: distances read the same both ways
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G:
ax.legend(title=G, fontsize=8)
plt.show()Needs pandas, numpy, matplotlib, scipy · reads pcoa-centroids-demo.csv · app theme from the optional codesplash helper
# Principal coordinates by group — Codesplash Chart Lab (recipe "pcoa-centroids")
# controls: center=centroid, spokes=false, hulls=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy.spatial import ConvexHull
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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
df = pd.read_csv("pcoa-centroids-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["management"] = pd.Categorical(df["management"].astype("string"), categories=["grazed", "mown", "natural"])
_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")
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
def centre(xy, how):
"""Centroid, or the spatial median by Weiszfeld's iterations from the mean (as in the app)."""
y = xy.mean(axis=0)
if how != "median":
return y
for _ in range(1000):
d = np.hypot(*(xy - y).T)
keep = d > 1e-15
if not keep.any():
return y
w = 1 / d[keep]
nxt = (xy[keep] * w[:, None]).sum(axis=0) / w.sum()
if np.hypot(*(nxt - y)) <= 1e-10 * (1 + np.hypot(*y)):
return nxt
y = nxt
return y
X = "PCoA 1 (31.4%)"
Y = "PCoA 2 (17.9%)"
G = "management"
CENTER, SPOKES, HULLS = "centroid", False, True
d = df.dropna(subset=[X, Y] + ([G] if G else []))
groups = levels_of(d[G]) if G else ["All rows"]
fig = go.Figure()
for i, k in enumerate(groups):
g = d[d[G].astype(str) == str(k)] if G else d
xy, col = g[[X, Y]].to_numpy(float), PALETTE[i % len(PALETTE)]
ctr = centre(xy, CENTER)
if HULLS and len(xy) >= 3:
try:
h = list(ConvexHull(xy).vertices)
h.append(h[0])
fig.add_scatter(x=xy[h, 0], y=xy[h, 1], mode="lines", fill="toself", fillcolor=rgba(col, 0.07), line=dict(color=col, width=1), showlegend=False, hoverinfo="skip")
except Exception:
pass
if SPOKES:
sx = [v for px in xy[:, 0] for v in (ctr[0], px, None)]
sy = [v for py in xy[:, 1] for v in (ctr[1], py, None)]
fig.add_scatter(x=sx, y=sy, mode="lines", line=dict(color=rgba(col, 0.3), width=0.8), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=xy[:, 0], y=xy[:, 1], mode="markers", name=f"{k} (n = {len(xy)})", marker=dict(color=col, symbol=SERIES_MARKERS[i % 8], size=6, opacity=0.6)) # shape per group, as in the app
if G:
fig.add_scatter(x=[ctr[0]], y=[ctr[1]], mode="markers", showlegend=False, marker=dict(symbol="diamond", size=11, color=col, line=dict(color="white", width=1.2)))
fig.update_layout(xaxis_title=X, yaxis_title=Y, legend_title_text=G or "")
fig.update_yaxes(scaleanchor="x", scaleratio=1) # equal units
fig.show()Needs pandas, numpy, plotly, scipy · reads pcoa-centroids-demo.csv · app theme from the optional codesplash helper
# Principal coordinates by group — Codesplash Chart Lab (recipe "pcoa-centroids")
# controls: center=centroid, spokes=false, hulls=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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("pcoa-centroids-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["management"]] <- factor(df[["management"]], levels = c("grazed", "mown", "natural"))
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
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
centre <- function(xy, how) {
y <- colMeans(xy) # centroid, or the spatial median by Weiszfeld's iterations from the mean
if (how != "median") return(y)
for (it in 1:1000) {
d <- sqrt(rowSums(sweep(xy, 2, y)^2)); keep <- d > 1e-15
if (!any(keep)) return(y)
w <- 1 / d[keep]
nxt <- colSums(xy[keep, , drop = FALSE] * w) / sum(w)
if (sqrt(sum((nxt - y)^2)) <= 1e-10 * (1 + sqrt(sum(y^2)))) return(nxt)
y <- nxt
}
y
}
x_col <- "PCoA 1 (31.4%)"
y_col <- "PCoA 2 (17.9%)"
g_col <- "management"
center <- "centroid"; show_spokes <- FALSE; show_hulls <- TRUE
keep <- !is.na(df[[x_col]]) & !is.na(df[[y_col]]) & (if (is.null(g_col)) TRUE else !is.na(df[[g_col]]))
d <- data.frame(x = df[[x_col]][keep], y = df[[y_col]][keep], k = if (is.null(g_col)) "All rows" else as.character(df[[g_col]][keep]))
ks <- if (is.null(g_col)) "All rows" else levels_of(df[[g_col]][keep])
d$k <- factor(d$k, levels = ks)
parts <- split(d, d$k, drop = TRUE)
ctr <- do.call(rbind, lapply(names(parts), function(k) { m <- centre(as.matrix(parts[[k]][c("x", "y")]), center); data.frame(k = k, cx = m[1], cy = m[2]) }))
ctr$k <- factor(ctr$k, levels = ks)
hulls <- do.call(rbind, lapply(parts, function(g) if (nrow(g) >= 3) g[grDevices::chull(g$x, g$y), ] else NULL))
spk <- merge(d, ctr, by = "k")
p <- ggplot(d, aes(x, y, colour = k)) +
{ if (show_hulls && !is.null(hulls)) geom_polygon(data = hulls, aes(fill = k), alpha = 0.07, show.legend = FALSE) } +
{ if (show_spokes) geom_segment(data = spk, aes(x = cx, y = cy, xend = x, yend = y), alpha = 0.3, linewidth = 0.3, show.legend = FALSE) } +
geom_point(aes(shape = k), size = 1.4, alpha = 0.6) + # shape per group, as in the app
{ if (!is.null(g_col)) geom_point(data = ctr, aes(cx, cy, fill = k), shape = 23, size = 3.2, colour = "white", stroke = 1, show.legend = FALSE) } +
scale_colour_manual(values = setNames(rep_len(cs_cat, length(ks)), ks)) +
scale_fill_manual(values = setNames(rep_len(cs_cat, length(ks)), ks)) +
scale_shape_manual(values = setNames(rep_len(cs_shapes, length(ks)), ks)) +
coord_equal() + # equal units: distances read the same both ways
labs(x = x_col, y = y_col, colour = g_col, shape = g_col) + theme_cs
print(p)Needs ggplot2 · reads pcoa-centroids-demo.csv · app theme from the optional codesplashr helper