svgsilhouette-plot
Silhouette plot
How well does each row fit its cluster compared with the next-nearest cluster?
How to read it
- Read each thin bar as one row's fit: near 1 is well inside its cluster.
- Compare clusters with the dashed average.
- Bars below zero: rows closer to another cluster.
- Callout 1: Wide bars: rows well inside this cluster.
- Callout 2: Dashed line: the average silhouette.
- 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
# Silhouette plot — Codesplash Chart Lab (recipe "silhouette-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("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 = go.Figure()
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()
fig.add_bar(x=w, y=np.arange(y0, y0 + len(w)), orientation="h", marker=dict(color=PALETTE[i % len(PALETTE)], line=dict(width=0)), name=str(k), width=1.0)
ticks.append(y0 + len(w) / 2)
y0 += len(w) + 3
avg = float(d[W].mean())
fig.add_vline(x=avg, line=dict(color=REF, dash="dash", width=1), annotation_text=f"average {avg:.2f}")
fig.update_yaxes(tickvals=ticks, ticktext=[str(k) for k in clusters], autorange="reversed", title=CL)
fig.update_layout(xaxis_title=W, bargap=0, showlegend=False)
fig.show()Needs pandas, numpy, plotly · reads silhouette-plot-demo.csv · app theme from the optional codesplash helper
# Silhouette plot — Codesplash Chart Lab (recipe "silhouette-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("silhouette-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["cluster"]] <- factor(df[["cluster"]], levels = c("1", "2", "3"))
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)]))
cl_col <- "cluster"
w_col <- "silhouette width"
d <- df[!is.na(df[[cl_col]]) & !is.na(df[[w_col]]), ]
d <- data.frame(k = factor(as.character(d[[cl_col]]), levels = levels_of(d[[cl_col]])), w = d[[w_col]])
d <- d[order(d$k, -d$w), ] # sorted within each cluster
d$pos <- seq_len(nrow(d)) + 3 * (as.integer(d$k) - 1)
mid <- tapply(d$pos, d$k, mean)
avg <- mean(d$w)
p <- ggplot(d, aes(w, pos, fill = k)) + geom_col(orientation = "y", width = 1) +
geom_vline(xintercept = avg, linetype = "dashed", colour = ref_col) + geom_vline(xintercept = 0, colour = "grey60") +
annotate("text", x = avg, y = 0, label = sprintf("average %.2f", avg), hjust = -0.05, vjust = 1, size = 3) +
scale_fill_manual(values = cs_cat, guide = "none") + scale_y_reverse(breaks = mid, labels = names(mid)) +
labs(x = w_col, y = cl_col) + theme_cs
print(p)Needs ggplot2 · reads silhouette-plot-demo.csv · app theme from the optional codesplashr helper