svgreachability-plot
Reachability plot (OPTICS)
Where are the dense regions, at every density at once?
How to read it
- Read left to right in OPTICS order.
- Read each valley as a cluster; deeper valleys are denser.
- Read the peaks between valleys as the boundaries.
- Callout 1: A valley: one cluster.
- Callout 2: A peak: a boundary between clusters.
- Callout 3: A shallower valley: a denser or sparser cluster.
Watch out
- Valleys can look deeper from the display's scale. A cut line gives a concrete clustering.
Defaults
- Cut (0 = none)
- 0
- Draw the reachability level that defines clusters; valleys below it become clusters.
- 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.
- Reachability of a row = max(core distance of its predecessor, distance to it); the first row of each region has none and is drawn as a faint full-height bar.
- Bars are coloured by the DBSCAN-equivalent clusters at the cut; noise is grey.
# Reachability plot (OPTICS) — Codesplash Chart Lab (recipe "reachability-plot")
# controls: cut=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("reachability-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["cluster"] = pd.Categorical(df["cluster"].astype("string"), categories=["1", "2", "3", "-1"])
_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)))
X = "OPTICS order"
R = "reachability distance"
K = "cluster"
U = "no reachability"
d = df.sort_values(X)
h = d[R].astype(float)
top = np.nanmax(h) * 1.05
fig, ax = plt.subplots(figsize=(8, 4))
no_reach = h.isna() | (d[U].astype(str).str.lower() == "true" if U else False)
ax.bar(d.loc[no_reach, X], top, width=1, color=GREY, label="no reachability")
clusters = levels_of(d[K]) if K else []
for i, k in enumerate(clusters):
g = d[(d[K].astype(str) == str(k)) & ~no_reach]
noise = str(k).lower() in ("noise", "-1")
ax.bar(g[X], g[R], width=1, color=GREY if noise else PALETTE[i % len(PALETTE)], label=str(k))
if not K:
g = d[~no_reach]
ax.bar(g[X], g[R], width=1, color=PALETTE[0])
ax.set_xlabel("OPTICS order")
ax.set_ylabel("reachability distance")
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads reachability-plot-demo.csv · app theme from the optional codesplash helper
# Reachability plot (OPTICS) — Codesplash Chart Lab (recipe "reachability-plot")
# controls: cut=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("reachability-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["cluster"] = pd.Categorical(df["cluster"].astype("string"), categories=["1", "2", "3", "-1"])
_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)))
X = "OPTICS order"
R = "reachability distance"
K = "cluster"
U = "no reachability"
d = df.sort_values(X)
no_reach = d[R].isna() | (d[U].astype(str).str.lower() == "true" if U else False)
fig = go.Figure()
fig.add_bar(x=d.loc[no_reach, X], y=[d[R].max() * 1.05] * int(no_reach.sum()), name="no reachability", marker_color=GREY)
for i, k in enumerate(levels_of(d[K]) if K else ["rows"]):
g = d[d[K].astype(str) == str(k)] if K else d
fig.add_bar(x=g[X], y=g[R], name=str(k), marker_color=GREY if str(k).lower() in ("noise", "-1") else PALETTE[i % len(PALETTE)])
fig.update_layout(barmode="overlay", bargap=0, xaxis_title="OPTICS order", yaxis_title="reachability distance")
fig.show()Needs pandas, numpy, plotly · reads reachability-plot-demo.csv · app theme from the optional codesplash helper
# Reachability plot (OPTICS) — Codesplash Chart Lab (recipe "reachability-plot")
# controls: cut=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("reachability-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["no reachability"]] <- as.logical(df[["no reachability"]])
df[["cluster"]] <- factor(df[["cluster"]], levels = c("1", "2", "3", "-1"))
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 <- "OPTICS order"
R <- "reachability distance"
K <- "cluster"
U <- "no reachability"
d <- data.frame(x = df[[X]], y = df[[R]], k = if (is.null(K)) "rows" else as.character(df[[K]]))
if (!is.null(U)) d$y[as.logical(df[[U]])] <- NA # the start of a region has no reachability
d$k[is.na(d$k)] <- "noise"
lv <- unique(d$k)
cols <- setNames(rep_len(cs_cat, length(lv)), lv)
cols[lv %in% c("noise", "-1")] <- grey_col
top <- max(d$y, na.rm = TRUE) * 1.05
d$y[!is.finite(d$y)] <- top
p <- ggplot(d, aes(x, y, fill = k)) +
geom_col(width = 1) +
scale_fill_manual(values = cols, name = NULL) +
labs(x = "OPTICS order", y = "reachability distance") + theme_cs
print(p)Needs ggplot2 · reads reachability-plot-demo.csv · app theme from the optional codesplashr helper