Skip to content
svgdendrogram

Dendrogram

How do rows merge into clusters, and where should the tree be cut?

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

How to read it

  1. Read from the leaves up: branches join where groups merge.
  2. Read join height as how different the merged groups are.
  3. Cut across a long vertical gap to get a natural number of clusters.
  1. Callout 1: A high join: very different groups.
  2. Callout 2: Low joins: very similar rows.
  3. Callout 3: The leaves are rows.

Watch out

  • The left-to-right order isn't meaningful: only the heights are.

Defaults

Cut into k clusters (0 = no cut)
0
Colour the tree as if cut into this many clusters.
Range 0 to 30, step 1

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.
  • Input is R's hclust merge matrix (scipy's linkage converts with leaves as negative 1-based numbers); leaves are ordered like hclust$order (left subtree first) and each merge sits midway between its children.
  • The cut for k clusters lies midway between the (n − k)-th and (n − k + 1)-th merge heights; branches below it take the cluster colours, left to right.
  • Leaf names are drawn up to 60 leaves.
# Dendrogram — Codesplash Chart Lab (recipe "dendrogram")
# controls: k=0
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("dendrogram-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 dendro_layout(df, ML, MR, H, k):
    a, b, h = df[ML].to_numpy(float), df[MR].to_numpy(float), df[H].to_numpy(float)
    ok = ~(np.isnan(a) | np.isnan(b) | np.isnan(h))
    merges = [(int(x), int(y), float(z)) for x, y, z in zip(a[ok], b[ok], h[ok])]
    m = len(merges)
    order, stack = [], [m]
    while stack:  # hclust order: depth first, left subtree first
        v = stack.pop()
        if v < 0:
            order.append(-v)
        else:
            stack += [merges[v - 1][1], merges[v - 1][0]]
    pos = {leaf: i for i, leaf in enumerate(order)}
    xs, leaves = [0.0] * m, [[] for _ in range(m)]
    xo = lambda v: pos[-v] if v < 0 else xs[v - 1]
    lv = lambda v: [-v] if v < 0 else leaves[v - 1]
    for i, (left, right, _) in enumerate(merges):
        xs[i] = (xo(left) + xo(right)) / 2
        leaves[i] = lv(left) + lv(right)
    k = int(round(k))
    below = m - (k - 1) if k >= 2 else m  # merges below the cut
    cluster, cut = {}, None
    if k >= 2:
        roots = [ch for i in range(below, m) for ch in merges[i][:2] if ch < 0 or ch - 1 < below]
        roots.sort(key=lambda v: min(pos[x] for x in lv(v)))
        for ci, rt in enumerate(roots):
            for x in lv(rt):
                cluster[x] = ci
        lo = merges[below - 1][2] if below >= 1 else 0.0
        cut = (lo + merges[below][2]) / 2
    return merges, order, xo, lv, below, cluster, cut
ML = "merge left"
MR = "merge right"
H = "height (Ward)"
LAB = "state"
K = 0  # cut into k clusters (0 = no cut)
merges, order, xo, lv, below, cluster, cut = dendro_layout(df, ML, MR, H, K)
labels = df[LAB].astype(str).tolist() if LAB else [str(i) for i in range(1, len(order) + 1)]
ho = lambda v: 0.0 if v < 0 else merges[v - 1][2]
fig, ax = plt.subplots(figsize=(9, 4.8))
for i, (left, right, h) in enumerate(merges):
    col = PALETTE[cluster[lv(left)[0]] % len(PALETTE)] if cluster and i < below else REF
    ax.plot([xo(left), xo(left), xo(right), xo(right)], [ho(left), h, h, ho(right)], color=col, linewidth=1.2)
if cut is not None:
    ax.axhline(cut, color="#ce5342", linestyle="--", linewidth=1)
ax.set_xticks(range(len(order)), [labels[x - 1] if x - 1 < len(labels) else str(x) for x in order], rotation=90, fontsize=8)
ax.set_ylabel(H)
ax.set_xlim(-0.5, len(order) - 0.5)
fig.tight_layout()
plt.show()

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