svgelbow-plot
Choosing k
How many clusters does the data support?
How to read it
- Read one panel per criterion against the number of clusters.
- Look for a bend or peak: the ringed point is the suggested k.
- Prefer a k that several criteria agree on, and that makes sense for your data.
- Callout 1: The elbow: extra clusters stop helping much.
- Callout 2: A peak: the best silhouette.
- Callout 3: The gap statistic's choice.
Watch out
- Elbows are often not sharp, and the criteria can disagree: there may be no natural k.
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.
- Criteria have different scales and directions (lower inertia / Davies–Bouldin is better, higher silhouette / Calinski–Harabasz / gap is better), so each gets its own panel and y-axis.
- The ringed point is the run's recommendation for that criterion (elbow by kneedle, maximum silhouette, gap's first k within one SE, …).
# Choosing k — Codesplash Chart Lab (recipe "elbow-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("elbow-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["criterion"] = pd.Categorical(df["criterion"].astype("string"), categories=["within-cluster SS", "silhouette", "gap statistic"])
_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 truthy(s):
return s.astype(str).str.strip().str.lower().isin(["true", "1", "yes", "t"])
K = "number of clusters k"
S = "score"
CRIT = "criterion"
CH = "recommended"
d = df.dropna(subset=[K, S]).sort_values(K)
crits = levels_of(d[CRIT]) if CRIT else [None]
fig, axes = plt.subplots(1, len(crits), figsize=(3.4 * len(crits) + 1, 3.8), squeeze=False)
for i, (ax, cr) in enumerate(zip(axes[0], crits)): # one panel per criterion (different scales)
g = d if cr is None else d[d[CRIT].astype(str) == str(cr)]
ax.plot(g[K], g[S], color=PALETTE[i % len(PALETTE)], marker="o", ms=4, linewidth=1.8)
if CH:
pick = g[truthy(g[CH])]
ax.scatter(pick[K], pick[S], s=180, facecolors="none", edgecolors=REF, linewidths=1.6, zorder=3)
ax.set_title(str(cr) if cr is not None else S, fontsize=10)
ax.set_xlabel(K)
fig.tight_layout()
plt.show()Needs pandas, numpy, matplotlib · reads elbow-plot-demo.csv · app theme from the optional codesplash helper
# Choosing k — Codesplash Chart Lab (recipe "elbow-plot")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
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("elbow-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["criterion"] = pd.Categorical(df["criterion"].astype("string"), categories=["within-cluster SS", "silhouette", "gap statistic"])
_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 truthy(s):
return s.astype(str).str.strip().str.lower().isin(["true", "1", "yes", "t"])
K = "number of clusters k"
S = "score"
CRIT = "criterion"
CH = "recommended"
d = df.dropna(subset=[K, S]).sort_values(K)
crits = levels_of(d[CRIT]) if CRIT else [None]
fig = make_subplots(rows=1, cols=len(crits), subplot_titles=[str(cr) if cr is not None else S for cr in crits])
for i, cr in enumerate(crits, start=1):
g = d if cr is None else d[d[CRIT].astype(str) == str(cr)]
fig.add_scatter(x=g[K], y=g[S], mode="lines+markers", line=dict(color=PALETTE[(i - 1) % len(PALETTE)], width=2), showlegend=False, row=1, col=i)
if CH:
pick = g[truthy(g[CH])]
fig.add_scatter(x=pick[K], y=pick[S], mode="markers", marker=dict(size=16, color="rgba(0,0,0,0)", line=dict(color=REF, width=2)), showlegend=False, row=1, col=i)
fig.update_xaxes(title_text=K, row=1, col=i)
fig.show()Needs pandas, numpy, plotly · reads elbow-plot-demo.csv · app theme from the optional codesplash helper
# Choosing k — Codesplash Chart Lab (recipe "elbow-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("elbow-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["recommended"]] <- as.logical(df[["recommended"]])
df[["criterion"]] <- factor(df[["criterion"]], levels = c("within-cluster SS", "silhouette", "gap statistic"))
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)]))
truthy <- function(v) tolower(trimws(as.character(v))) %in% c("true", "1", "yes", "t")
k_col <- "number of clusters k"
s_col <- "score"
crit_col <- "criterion"
ch_col <- "recommended"
d <- df[!is.na(df[[k_col]]) & !is.na(df[[s_col]]), ]
d <- data.frame(k = d[[k_col]], s = d[[s_col]], crit = if (is.null(crit_col)) s_col else factor(as.character(d[[crit_col]]), levels = levels_of(d[[crit_col]])),
chosen = if (is.null(ch_col)) FALSE else truthy(d[[ch_col]]))
d <- d[order(d$crit, d$k), ]
p <- ggplot(d, aes(k, s, colour = crit)) + geom_line(linewidth = 0.8) + geom_point(size = 1.8) +
geom_point(data = d[d$chosen, ], shape = 21, size = 5, stroke = 1.1, colour = ref_col, fill = NA) + # the recommended k
facet_wrap(~crit, scales = "free_y", nrow = 1) + scale_colour_manual(values = cs_cat, guide = "none") +
labs(x = k_col, y = s_col) + theme_cs
print(p)Needs ggplot2 · reads elbow-plot-demo.csv · app theme from the optional codesplashr helper