svgcluster-scatter
Cluster map
Which rows group together, and how well separated are the groups?
How to read it
- Read colour as the cluster a row was assigned to.
- Check separation: are clusters distinct, or touching?
- Grey points are noise, assigned to no cluster.
- Callout 1: A cluster with its centre.
- Callout 2: Another, well separated.
- Callout 3: Grey: noise.
Watch out
- Clustering always returns clusters, even from noise. Check stability before you name them.
- A 2-D map can show separation that isn't in the full data, or hide it.
Defaults
- Convex hull per cluster
- Off
- Outline each cluster with the smallest shape enclosing its points.
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.
- Clusters are the run's labels after canonicalization (1…k by size, largest first); −1 is noise (DBSCAN/HDBSCAN) and is drawn grey and listed last.
- Rows flagged as centres (k-means centroids, PAM medoids projected into the same space) are drawn as diamonds.
- Distances on a UMAP or t-SNE map are not faithful — use the map to see groups, not to measure them.
# Cluster map — Codesplash Chart Lab (recipe "cluster-scatter")
# controls: hull=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]
df = pd.read_csv("cluster-scatter-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")
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 is_noise(v):
return str(v).strip().lower() in ("-1", "noise", "outlier")
def truthy(s):
return s.astype(str).str.strip().str.lower().isin(["true", "1", "yes", "t"])
X = "PC1"
Y = "PC2"
CL = "cluster"
CEN = "centre"
LAB = None
HULL = False # convex hull around each cluster
d = df.dropna(subset=[X, Y, CL])
cen = truthy(d[CEN]) if CEN else pd.Series(False, index=d.index)
pts, centres = d[~cen], d[cen]
clusters = [k for k in levels_of(pts[CL]) if not is_noise(k)]
fig, ax = plt.subplots(figsize=(7, 6))
noise = pts[pts[CL].map(is_noise)]
if len(noise):
ax.scatter(noise[X], noise[Y], s=8, color=GREY, label="noise")
for i, k in enumerate(clusters):
g = pts[pts[CL].astype(str) == str(k)]
col = PALETTE[i % len(PALETTE)]
ax.scatter(g[X], g[Y], s=10, alpha=0.75, color=col, marker=SERIES_MARKERS[i % 8], label=str(k)) # shape per cluster (noise stays round), as in the app
if HULL and len(g) >= 3:
xy = g[[X, Y]].to_numpy(float)
h = ConvexHull(xy).vertices
ax.fill(xy[h, 0], xy[h, 1], color=col, alpha=0.08, edgecolor=col, linewidth=1)
ax.scatter(centres[X], centres[Y], marker="X", s=140, color="white", edgecolors=REF, linewidths=1.5, zorder=3, label="centre" if len(centres) else None)
if LAB:
for _, row in centres.iterrows():
ax.annotate(str(row[LAB]), (row[X], row[Y]), xytext=(6, 6), textcoords="offset points", fontsize=8)
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.legend(title=CL, fontsize=8, markerscale=1.5)
plt.show()Needs pandas, numpy, matplotlib, scipy · reads cluster-scatter-demo.csv · app theme from the optional codesplash helper
# Cluster map — Codesplash Chart Lab (recipe "cluster-scatter")
# controls: hull=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy.spatial import ConvexHull
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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
df = pd.read_csv("cluster-scatter-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")
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 is_noise(v):
return str(v).strip().lower() in ("-1", "noise", "outlier")
def truthy(s):
return s.astype(str).str.strip().str.lower().isin(["true", "1", "yes", "t"])
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
X = "PC1"
Y = "PC2"
CL = "cluster"
CEN = "centre"
LAB = None
HULL = False
d = df.dropna(subset=[X, Y, CL])
cen = truthy(d[CEN]) if CEN else pd.Series(False, index=d.index)
pts, centres = d[~cen], d[cen]
clusters = [k for k in levels_of(pts[CL]) if not is_noise(k)]
fig = go.Figure()
noise = pts[pts[CL].map(is_noise)]
if len(noise):
fig.add_scattergl(x=noise[X], y=noise[Y], mode="markers", name="noise", marker=dict(color=GREY, size=4))
for i, k in enumerate(clusters):
g = pts[pts[CL].astype(str) == str(k)]
col = PALETTE[i % len(PALETTE)]
if HULL and len(g) >= 3:
xy = g[[X, Y]].to_numpy(float)
h = list(ConvexHull(xy).vertices) + [ConvexHull(xy).vertices[0]]
fig.add_scatter(x=xy[h, 0], y=xy[h, 1], mode="lines", fill="toself", fillcolor=rgba(col, 0.08), line=dict(color=col, width=1), showlegend=False, hoverinfo="skip")
fig.add_scattergl(x=g[X], y=g[Y], mode="markers", name=str(k), marker=dict(color=col, symbol=SERIES_MARKERS[i % 8], size=5, opacity=0.75)) # shape per cluster, as in the app
if len(centres):
fig.add_scatter(x=centres[X], y=centres[Y], mode="markers+text" if LAB else "markers", name="centre", text=centres[LAB].astype(str) if LAB else None,
textposition="top right", marker=dict(symbol="x", size=13, color="white", line=dict(color=REF, width=1.5)))
fig.update_layout(xaxis_title=X, yaxis_title=Y, legend_title_text=CL)
fig.show()Needs pandas, numpy, plotly, scipy · reads cluster-scatter-demo.csv · app theme from the optional codesplash helper
# Cluster map — Codesplash Chart Lab (recipe "cluster-scatter")
# controls: hull=false
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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("cluster-scatter-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["centre"]] <- as.logical(df[["centre"]])
df[["cluster"]] <- factor(df[["cluster"]])
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)]))
is_noise <- function(v) tolower(trimws(as.character(v))) %in% c("-1", "noise", "outlier")
truthy <- function(v) tolower(trimws(as.character(v))) %in% c("true", "1", "yes", "t")
x_col <- "PC1"
y_col <- "PC2"
cl_col <- "cluster"
cen_col <- "centre"
lab_col <- NULL
show_hull <- FALSE # convex hull around each cluster
d <- df[!is.na(df[[x_col]]) & !is.na(df[[y_col]]) & !is.na(df[[cl_col]]), ]
d <- data.frame(x = d[[x_col]], y = d[[y_col]], k = as.character(d[[cl_col]]), cen = if (is.null(cen_col)) FALSE else truthy(d[[cen_col]]),
lab = if (is.null(lab_col)) "" else as.character(d[[lab_col]]))
pts <- d[!d$cen, ]; centres <- d[d$cen, ]
ks <- setdiff(levels_of(pts$k), pts$k[is_noise(pts$k)])
pts$k <- ifelse(is_noise(pts$k), "noise", pts$k)
pts$k <- factor(pts$k, levels = c(ks, "noise"))
hulls <- do.call(rbind, lapply(split(pts[pts$k != "noise", ], pts$k[pts$k != "noise"], drop = TRUE), function(g) if (nrow(g) >= 3) g[grDevices::chull(g$x, g$y), ] else NULL))
p <- ggplot(pts, aes(x, y, colour = k)) +
{ if (show_hull && !is.null(hulls)) geom_polygon(data = hulls, aes(fill = k), alpha = 0.08, show.legend = FALSE) } +
geom_point(aes(shape = k), size = 1.2, alpha = 0.75) + # shape per cluster (noise stays round), as in the app
geom_point(data = centres, shape = 4, size = 4, stroke = 1.6, colour = ref_col) +
{ if (!is.null(lab_col) && nrow(centres)) geom_text(data = centres, aes(label = lab), colour = ref_col, hjust = -0.2, vjust = -0.6, size = 3) } +
scale_colour_manual(values = c(setNames(rep_len(cs_cat, length(ks)), ks), noise = grey_col)) +
scale_fill_manual(values = setNames(rep_len(cs_cat, length(ks)), ks)) +
scale_shape_manual(values = c(setNames(rep_len(cs_shapes, length(ks)), ks), noise = cs_shapes[1])) +
labs(x = x_col, y = y_col, colour = cl_col, shape = cl_col) + theme_cs
print(p)Needs ggplot2 · reads cluster-scatter-demo.csv · app theme from the optional codesplashr helper