svgscree-plot
Scree plot
How many components carry most of the variance?
How to read it
- Read each bar as the variance one component carries.
- Read the line as the running total.
- Stop where bars flatten, or at a total share you need.
- Callout 1: The first component's share.
- Callout 2: The running total.
- Callout 3: Small bars: little beyond noise.
Watch out
- Without scaling, components mostly reflect the columns with the largest units.
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.
- Variance shares are proportions (eigenvalue ÷ total); the cumulative line is the engine's when sent, else the running sum.
# Scree plot — Codesplash Chart Lab (recipe "scree-plot")
# 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("scree-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
COMP = "component"
VAR = "share of variance"
CUM = None
d = df.dropna(subset=[COMP, VAR]).sort_values(COMP)
cum = d[CUM] if CUM else d[VAR].cumsum()
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.bar(d[COMP].astype(str), d[VAR], color=PALETTE[0], label=VAR)
ax.plot(d[COMP].astype(str), cum, color=REF, marker="o", ms=4, linewidth=1.6, label="cumulative")
for x, v in zip(d[COMP].astype(str), d[VAR]):
ax.annotate(f"{v:.0%}" if d[VAR].max() <= 1 else f"{v:.3g}", (x, v), xytext=(0, 3), textcoords="offset points", ha="center", fontsize=8)
ax.set_xlabel(COMP)
ax.set_ylabel(VAR)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads scree-plot-demo.csv · app theme from the optional codesplash helper
# Scree plot — Codesplash Chart Lab (recipe "scree-plot")
# 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("scree-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
COMP = "component"
VAR = "share of variance"
CUM = None
d = df.dropna(subset=[COMP, VAR]).sort_values(COMP)
cum = d[CUM] if CUM else d[VAR].cumsum()
fig = go.Figure()
fig.add_bar(x=d[COMP].astype(str), y=d[VAR], name=VAR, marker_color=PALETTE[0], text=[f"{v:.0%}" if d[VAR].max() <= 1 else f"{v:.3g}" for v in d[VAR]], textposition="outside")
fig.add_scatter(x=d[COMP].astype(str), y=cum, mode="lines+markers", name="cumulative", line=dict(color=REF, width=2))
fig.update_layout(xaxis_title=COMP, yaxis_title=VAR)
fig.show()Needs pandas, numpy, plotly · reads scree-plot-demo.csv · app theme from the optional codesplash helper
# Scree plot — Codesplash Chart Lab (recipe "scree-plot")
# 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("scree-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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
comp_col <- "component"
var_col <- "share of variance"
cum_col <- NULL
d <- df[!is.na(df[[comp_col]]) & !is.na(df[[var_col]]), ]
d <- d[order(d[[comp_col]]), ]
d <- data.frame(comp = factor(as.character(d[[comp_col]]), levels = unique(as.character(d[[comp_col]]))), v = d[[var_col]],
cum = if (is.null(cum_col)) cumsum(d[[var_col]]) else d[[cum_col]])
fmt <- if (max(d$v) <= 1) function(v) sprintf("%.0f%%", 100 * v) else function(v) format(signif(v, 3))
p <- ggplot(d, aes(comp)) + geom_col(aes(y = v), fill = cs_cat[1], width = 0.7) +
geom_text(aes(y = v, label = fmt(v)), vjust = -0.4, size = 3) +
geom_line(aes(y = cum, group = 1), colour = ref_col, linewidth = 0.8) + geom_point(aes(y = cum), colour = ref_col, size = 1.8) +
labs(x = comp_col, y = var_col) + theme_cs
print(p)Needs ggplot2 · reads scree-plot-demo.csv · app theme from the optional codesplashr helper