Skip to content
svgcanonical-plot

Canonical discriminant plot

Along which combinations of the outcomes do the groups separate, and which outcomes drive it?

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

How to read it

  1. Read points as rows on the combinations that best separate the groups.
  2. Read circles as confidence regions for each group's mean.
  3. Read arrows as outcomes: the direction each one drives.
  1. Callout 1: A group's mean and confidence circle.
  2. Callout 2: An outcome's direction.
  3. Callout 3: How much group separation this axis carries.

Watch out

  • The display only captures two dimensions. Check how much each axis explains.

Defaults

Show structure coefficients
On
Draw arrows for how each outcome relates to the canonical axes.

Pinned in the code

  • Draws the engine's canonical scores as given: coefficients scale each dimension to unit pooled within-group variance, so groups' clouds are circular and a circle of radius √(χ²(level)/nⱼ) is the confidence region of a group mean.
  • Both axes share one scale, so distances read directly as standardized (Mahalanobis) distances.
  • Arrows are structure coefficients — correlations of each outcome with the canonical scores — multiplied by one factor so the longest reaches 80% of the plot (the angle, not the length, carries meaning).
  • With one canonical dimension (two groups or a one-df effect) groups are stacked on separate lines.
# Canonical discriminant plot — Codesplash Chart Lab (recipe "canonical-plot")
# controls: vectors=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"]
# 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("canonical-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["species"] = pd.Categorical(df["species"].astype("string"), categories=["setosa", "versicolor", "virginica", ""])

_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)))
X = "Can1 (r = 0.98)"
Y = "Can2 (r = 0.47)"
G = "species"
KIND = "kind"
LAB = "label"
RAD = "95% radius of the mean"
kind = df[KIND].astype(str).str.lower()
points, means, struct = df[~kind.str.startswith("struct") & (kind != "mean")], df[kind == "mean"], df[kind.str.startswith("struct")]
fig, ax = plt.subplots(figsize=(7, 5))
for i, k in enumerate(levels_of(points[G])):
    g, col = points[points[G].astype(str) == str(k)], PALETTE[i % len(PALETTE)]
    ax.scatter(g[X], g[Y] if Y else 0 * g[X], s=12, color=col, alpha=0.5, marker=SERIES_MARKERS[i % 8], label=k)  # shape per group, as in the app
    for _, m in means[means[G].astype(str) == str(k)].iterrows():
        my = m[Y] if Y else 0
        ax.scatter([m[X]], [my], marker=SERIES_MARKERS[i % 8], s=50, color=col, edgecolors="white")
        if RAD and pd.notna(m[RAD]):
            ax.add_patch(plt.Circle((m[X], my), m[RAD], fill=False, color=col))
for _, s in struct.iterrows():
    sy = s[Y] if Y else 0
    ax.annotate("", xy=(s[X], sy), xytext=(0, 0), arrowprops=dict(arrowstyle="->", color=REF))
    ax.text(s[X], sy, s[LAB] if LAB else "", fontsize=8)
    ax.update_datalim([(s[X], sy)])
ax.autoscale_view()
ax.axhline(0, color=REF, linewidth=0.6, linestyle=":")
ax.axvline(0, color=REF, linewidth=0.6, linestyle=":")
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads canonical-plot-demo.csv · app theme from the optional codesplash helper