svgk-distance
k-distance curve
Which neighbourhood radius (eps) separates dense rows from sparse ones?
How to read it
- Read rows sorted by distance to their k-th neighbour.
- The ringed knee is where distances begin to climb.
- Use the distance at the knee for eps: rows above it become noise.
- Callout 1: The knee: a candidate for eps.
- Callout 2: Flat region: rows in dense areas.
- 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
# k-distance curve — Codesplash Chart Lab (recipe "k-distance")
# controls: eps=0
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("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 = go.Figure()
fig.add_scatter(x=d[X], y=d[D], mode="lines", line=dict(color=PALETTE[0]), name="sorted k-distance")
if eps:
fig.add_hline(y=eps, line_dash="dash", line_color=REF, annotation_text=f"eps = {eps:.3g}")
fig.update_layout(xaxis_title="rows (sorted)", yaxis_title=D)
fig.show()Needs pandas, numpy, plotly · reads k-distance-demo.csv · app theme from the optional codesplash helper
# k-distance curve — Codesplash Chart Lab (recipe "k-distance")
# controls: eps=0
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("k-distance-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["chosen eps"]] <- as.logical(df[["chosen eps"]])
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
X <- "rows (sorted)"
D <- "distance to the 5th neighbour"
CH <- "chosen eps"
d <- data.frame(x = df[[X]], y = df[[D]], chosen = if (is.null(CH)) FALSE else as.logical(df[[CH]]))
d <- d[is.finite(d$x) & is.finite(d$y), ]
d <- d[order(d$x), ]
eps <- 0
if (!eps && any(d$chosen, na.rm = TRUE)) eps <- d$y[which(d$chosen)[1]]
p <- ggplot(d, aes(x, y)) +
geom_line(colour = cs_cat[[1]]) +
(if (eps) geom_hline(yintercept = eps, colour = ref_col, linetype = "dashed")) +
geom_point(data = d[which(d$chosen), ], shape = 1, size = 3, colour = ref_col) +
labs(x = "rows (sorted)", y = D) + theme_cs
print(p)Needs ggplot2 · reads k-distance-demo.csv · app theme from the optional codesplashr helper