Skip to content
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?

Demo data · seed 20261101 · 54 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read points as rows placed so that distances match their dissimilarities.
  2. Read diamonds as group centres.
  3. Separated centres suggest different locations; different hull sizes suggest different spreads.
  1. Callout 1: A group centre.
  2. Callout 2: Hull: the group's spread.
  3. 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