svgcanonical-plot
Canonical discriminant plot
Along which combinations of the outcomes do the groups separate, and which outcomes drive it?
How to read it
- Read points as rows on the combinations that best separate the groups.
- Read circles as confidence regions for each group's mean.
- Read arrows as outcomes: the direction each one drives.
- Callout 1: A group's mean and confidence circle.
- Callout 2: An outcome's direction.
- 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
# Canonical discriminant plot — Codesplash Chart Lab (recipe "canonical-plot")
# controls: vectors=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
# 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("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 = go.Figure()
for i, k in enumerate(levels_of(points[G])):
g, col = points[points[G].astype(str) == str(k)], PALETTE[i % len(PALETTE)]
fig.add_scatter(x=g[X], y=g[Y] if Y else 0 * g[X], mode="markers", marker=dict(color=col, size=6, opacity=0.5, symbol=SERIES_MARKERS[i % 8]), name=str(k)) # shape per group, as in the app
m = means[means[G].astype(str) == str(k)]
fig.add_scatter(x=m[X], y=m[Y] if Y else 0 * m[X], mode="markers", marker=dict(color=col, size=11, symbol=SERIES_MARKERS[i % 8], line=dict(color="white", width=1)), showlegend=False)
for _, q in m.iterrows():
if RAD and pd.notna(q[RAD]):
qy = q[Y] if Y else 0
fig.add_shape(type="circle", x0=q[X] - q[RAD], x1=q[X] + q[RAD], y0=qy - q[RAD], y1=qy + q[RAD], line=dict(color=col))
for _, s in struct.iterrows():
fig.add_annotation(x=s[X], y=s[Y] if Y else 0, ax=0, ay=0, axref="x", ayref="y", text=str(s[LAB]) if LAB else "", showarrow=True, arrowhead=2, arrowcolor=REF)
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()Needs pandas, numpy, plotly · reads canonical-plot-demo.csv · app theme from the optional codesplash helper
# Canonical discriminant plot — Codesplash Chart Lab (recipe "canonical-plot")
# controls: vectors=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("canonical-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["species"]] <- factor(df[["species"]], levels = c("setosa", "versicolor", "virginica", ""))
df[["kind"]] <- factor(df[["kind"]])
df[["label"]] <- factor(df[["label"]])
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)]))
X <- "Can1 (r = 0.98)"
Y <- "Can2 (r = 0.47)"
G <- "species"
KIND <- "kind"
LAB <- "label"
RAD <- "95% radius of the mean"
d <- data.frame(x = df[[X]], y = if (is.null(Y)) 0 else df[[Y]], g = as.character(df[[G]]), kind = tolower(as.character(df[[KIND]])), label = if (is.null(LAB)) "" else as.character(df[[LAB]]), r = if (is.null(RAD)) NA_real_ else df[[RAD]])
points <- d[!startsWith(d$kind, "struct") & d$kind != "mean", ]
means <- d[d$kind == "mean", ]
struct <- d[startsWith(d$kind, "struct"), ]
theta <- seq(0, 2 * pi, length.out = 73)
circles <- do.call(rbind, lapply(which(is.finite(means$r)), function(i) data.frame(x = means$x[i] + means$r[i] * cos(theta), y = means$y[i] + means$r[i] * sin(theta), g = means$g[i])))
p <- ggplot() +
geom_hline(yintercept = 0, colour = ref_col, linewidth = 0.2, linetype = "dotted") +
geom_vline(xintercept = 0, colour = ref_col, linewidth = 0.2, linetype = "dotted") +
geom_point(aes(x, y, colour = g, shape = g), points, size = 1.2, alpha = 0.5) + # shape per group, as in the app
geom_point(aes(x, y, colour = g, shape = g), means, size = 3) +
(if (!is.null(circles)) geom_path(aes(x, y, colour = g), circles)) +
geom_segment(aes(0, 0, xend = x, yend = y), struct, colour = ref_col, arrow = arrow(length = unit(0.15, "cm"))) +
geom_text(aes(x, y, label = label), struct, size = 2.6, vjust = -0.6) +
scale_colour_manual(values = cs_cat, name = NULL) + scale_shape_manual(values = cs_shapes, name = NULL) +
labs(x = X, y = if (is.null(Y)) "" else Y) + theme_cs
print(p)Needs ggplot2 · reads canonical-plot-demo.csv · app theme from the optional codesplashr helper