Skip to content
svgcluster-scatter

Cluster map

Which rows group together, and how well separated are the groups?

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

How to read it

  1. Read colour as the cluster a row was assigned to.
  2. Check separation: are clusters distinct, or touching?
  3. Grey points are noise, assigned to no cluster.
  1. Callout 1: A cluster with its centre.
  2. Callout 2: Another, well separated.
  3. 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