Skip to content
svgsilhouette-plot

Silhouette plot

How well does each row fit its cluster compared with the next-nearest cluster?

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

How to read it

  1. Read each thin bar as one row's fit: near 1 is well inside its cluster.
  2. Compare clusters with the dashed average.
  3. Bars below zero: rows closer to another cluster.
  1. Callout 1: Wide bars: rows well inside this cluster.
  2. Callout 2: Dashed line: the average silhouette.
  3. Callout 3: Near zero: rows on a boundary.

Watch out

  • Silhouette favours round, equally sized clusters, and can miss valid long or nested ones.

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.
  • Widths s(i) = (b − a) / max(a, b) from the engine (a = mean distance to the own cluster, b = to the nearest other); the chart sorts them within each cluster and draws each cluster as one filled profile, so any number of rows stays light.
  • Rule of thumb (Kaufman & Rousseeuw): average > 0.7 strong, 0.5–0.7 reasonable, 0.25–0.5 weak structure.
# Silhouette plot — Codesplash Chart Lab (recipe "silhouette-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("silhouette-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["cluster"] = pd.Categorical(df["cluster"].astype("string"), categories=["1", "2", "3"])

_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)))
CL = "cluster"
W = "silhouette width"
d = df.dropna(subset=[CL, W])
clusters = levels_of(d[CL])
fig, ax = plt.subplots(figsize=(7, 6))
y0, ticks = 0, []
for i, k in enumerate(clusters):
    w = d.loc[d[CL].astype(str) == str(k), W].sort_values(ascending=False).to_numpy()  # sorted within the cluster
    ax.barh(np.arange(y0, y0 + len(w)), w, height=1.0, color=PALETTE[i % len(PALETTE)], linewidth=0)
    ticks.append(y0 + len(w) / 2)
    y0 += len(w) + 3
avg = d[W].mean()
ax.axvline(avg, color=REF, linestyle="--", linewidth=1, label=f"average {avg:.2f}")
ax.axvline(0, color="grey", linewidth=0.8)
ax.set_yticks(ticks, [str(k) for k in clusters])
ax.invert_yaxis()
ax.set_xlabel(W)
ax.set_ylabel(CL)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads silhouette-plot-demo.csv · app theme from the optional codesplash helper