Skip to content
svgelbow-plot

Choosing k

How many clusters does the data support?

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

How to read it

  1. Read one panel per criterion against the number of clusters.
  2. Look for a bend or peak: the ringed point is the suggested k.
  3. Prefer a k that several criteria agree on, and that makes sense for your data.
  1. Callout 1: The elbow: extra clusters stop helping much.
  2. Callout 2: A peak: the best silhouette.
  3. 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