svgbiplot
PCA biplot
How do rows spread on the main components, and which variables drive each direction?
How to read it
- Read points as rows on the first two components.
- Read arrows as variables: long arrows contribute more.
- Rows far along an arrow have high values for that variable.
- Callout 1: An arrow: this variable's direction.
- Callout 2: A row far along this direction.
- Callout 3: Rows on the other side: low values.
Watch out
- It shows only part of the variance: check the percentages on the axes before you trust distances.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
- Loadings are multiplied by one factor so the longest arrow reaches 80% of the largest score (the legend shows the factor); arrow lengths compare variables, not rows.
- Both axes share one scale so angles between arrows read as correlations.
# PCA biplot — Codesplash Chart Lab (recipe "biplot")
# controls: defaults
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("biplot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["point", "loading"])
_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 = "PC1 (62%)"
Y = "PC2 (25%)"
KIND = "kind"
LAB = "label"
d = df.dropna(subset=[X, Y])
load = d[KIND].astype(str).str.lower().str.startswith("load")
pts, ld = d[~load], d[load]
reach = float(np.abs(pts[[X, Y]].to_numpy()).max()) if len(pts) else 1.0
longest = float(np.hypot(ld[X], ld[Y]).max()) if len(ld) else 1.0
scale = 0.8 * reach / longest if len(pts) else 1.0 # longest arrow reaches 80% of the score extent
fig, ax = plt.subplots(figsize=(7, 6))
ax.axhline(0, color="grey", linewidth=0.6)
ax.axvline(0, color="grey", linewidth=0.6)
ax.scatter(pts[X], pts[Y], s=16, color=PALETTE[0], alpha=0.8)
for _, row in pts.iterrows():
ax.annotate(str(row[LAB]), (row[X], row[Y]), xytext=(3, 3), textcoords="offset points", fontsize=7, color=GREY if len(pts) > 40 else REF)
for _, row in ld.iterrows():
ax.annotate("", xy=(row[X] * scale, row[Y] * scale), xytext=(0, 0), arrowprops=dict(arrowstyle="->", color="#ce5342", lw=1.4))
ax.annotate(str(row[LAB]), (row[X] * scale, row[Y] * scale), xytext=(4, 4), textcoords="offset points", fontsize=9, color="#ce5342")
ax.set_xlabel(X)
ax.set_ylabel(Y)
plt.show()Needs pandas, numpy, matplotlib · reads biplot-demo.csv · app theme from the optional codesplash helper
# PCA biplot — Codesplash Chart Lab (recipe "biplot")
# controls: defaults
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("biplot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["point", "loading"])
_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 = "PC1 (62%)"
Y = "PC2 (25%)"
KIND = "kind"
LAB = "label"
d = df.dropna(subset=[X, Y])
load = d[KIND].astype(str).str.lower().str.startswith("load")
pts, ld = d[~load], d[load]
reach = float(np.abs(pts[[X, Y]].to_numpy()).max()) if len(pts) else 1.0
longest = float(np.hypot(ld[X], ld[Y]).max()) if len(ld) else 1.0
scale = 0.8 * reach / longest if len(pts) else 1.0
fig = go.Figure()
fig.add_scatter(x=pts[X], y=pts[Y], mode="markers+text", text=pts[LAB].astype(str), textposition="top right", textfont=dict(size=9),
marker=dict(color=PALETTE[0], size=7, opacity=0.8), name="scores")
for _, row in ld.iterrows():
fig.add_annotation(x=row[X] * scale, y=row[Y] * scale, ax=0, ay=0, xref="x", yref="y", axref="x", ayref="y", text=str(row[LAB]),
showarrow=True, arrowhead=2, arrowcolor="#ce5342", font=dict(color="#ce5342"))
fig.update_layout(xaxis_title=X, yaxis_title=Y, showlegend=False)
fig.show()Needs pandas, numpy, plotly · reads biplot-demo.csv · app theme from the optional codesplash helper
# PCA biplot — Codesplash Chart Lab (recipe "biplot")
# controls: defaults
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("biplot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["kind"]] <- factor(df[["kind"]], levels = c("point", "loading"))
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
x_col <- "PC1 (62%)"
y_col <- "PC2 (25%)"
kind_col <- "kind"
lab_col <- "label"
d <- df[!is.na(df[[x_col]]) & !is.na(df[[y_col]]), ]
d <- data.frame(x = d[[x_col]], y = d[[y_col]], load = startsWith(tolower(as.character(d[[kind_col]])), "load"), lab = as.character(d[[lab_col]]))
pts <- d[!d$load, ]; ld <- d[d$load, ]
scale <- if (nrow(pts) && nrow(ld)) 0.8 * max(abs(c(pts$x, pts$y))) / max(sqrt(ld$x^2 + ld$y^2)) else 1 # longest arrow = 80% of the score extent
ld$x <- ld$x * scale; ld$y <- ld$y * scale
p <- ggplot(pts, aes(x, y)) + geom_hline(yintercept = 0, colour = "grey75") + geom_vline(xintercept = 0, colour = "grey75") +
geom_point(colour = cs_cat[1], alpha = 0.8, size = 1.6) + geom_text(aes(label = lab), size = 2.5, hjust = -0.15, vjust = -0.3, colour = ref_col) +
geom_segment(data = ld, aes(x = 0, y = 0, xend = x, yend = y), arrow = grid::arrow(length = grid::unit(0.15, "cm")), colour = "#ce5342") +
geom_text(data = ld, aes(label = lab), colour = "#ce5342", size = 3.2, hjust = -0.1, vjust = -0.4) +
labs(x = x_col, y = y_col) + theme_cs
print(p)Needs ggplot2 · reads biplot-demo.csv · app theme from the optional codesplashr helper