Skip to content
svgk-distance

k-distance curve

Which neighbourhood radius (eps) separates dense rows from sparse ones?

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

How to read it

  1. Read rows sorted by distance to their k-th neighbour.
  2. The ringed knee is where distances begin to climb.
  3. Use the distance at the knee for eps: rows above it become noise.
  1. Callout 1: The knee: a candidate for eps.
  2. Callout 2: Flat region: rows in dense areas.
  3. Callout 3: Steep end: isolated rows.

Watch out

  • Clusters of different densities don't share one eps: consider OPTICS.

Defaults

eps line (0 = the chosen row)
0
Draw the distance you are considering for eps; 0 uses the knee.
Range 0 to 1,000,000,000, step 0.01

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.
  • k-distance = distance to the k-th nearest row with the row itself counted (k = minimum neighbours), as dbscan::kNNdist(k − 1) and scikit-learn's NearestNeighbors(k).
  • The knee is the point farthest from the chord between the curve's end points on normalized axes (kneedle).
# k-distance curve — Codesplash Chart Lab (recipe "k-distance")
# controls: eps=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("k-distance-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")
X = "rows (sorted)"
D = "distance to the 5th neighbour"
CH = "chosen eps"
d = df.dropna(subset=[X, D]).sort_values(X)
eps = 0
chosen = d[d[CH].astype(str).str.lower() == "true"] if CH else d.iloc[:0]
if not eps and len(chosen):
    eps = float(chosen[D].iloc[0])
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(d[X], d[D], color=PALETTE[0], label="sorted k-distance")
if len(chosen):
    ax.scatter(chosen[X], chosen[D], s=50, facecolor="none", edgecolor=REF, zorder=3)
if eps:
    ax.axhline(eps, color=REF, linestyle="--", linewidth=1, label=f"eps = {eps:.3g}")
ax.set_xlabel("rows (sorted)")
ax.set_ylabel(D)
ax.legend(fontsize=8)
plt.show()

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