svgripley-envelope
Ripley's L with envelopes
At what distances are points more clustered or more regular than random?
How to read it
- Read x as distance and y as how far the points are from random at that distance.
- Above the envelope, points are closer together than random; below it, more evenly spaced.
- Use the dashed global envelope to judge the whole curve, and the shaded band for one chosen distance.
- Callout 1: Above the global envelope: clustered at these distances.
- Callout 2: Pointwise envelope from random patterns.
- Callout 3: Global envelope: the test of the whole curve.
- Callout 4: A random pattern sits on this line.
Watch out
- Reading the shaded band at every distance finds false signals: a pointwise envelope is left somewhere far more often than its level says.
- Density that varies across the window also looks like clustering, so this alone doesn't show that points attract each other.
Defaults
- Subtract r
- On
- Draw L(r) − r so a random pattern is the flat line at 0; off draws L(r) against the line L = r.
- Significance level
- 0.05
- The level the envelopes were simulated at; it labels the legend.
- Range 0.001 to 0.2, step 0.005
Pinned in the code
- L(r) = √(K(r)/π) stabilizes the variance of Ripley's K, and L(r) = r under complete spatial randomness.
- Use the global envelope to test the whole curve. A pointwise envelope is exceeded somewhere far more often than its level suggests, so read it distance by distance only.
- Results depend on the observation window; a window much larger than the points' range makes any pattern look clustered.
Use with care
Clustering at a distance can also come from density that varies across the window. It does not by itself mean points attract one another.
# Ripley's L with envelopes — Codesplash Chart Lab (recipe "ripley-envelope")
# controls: centred=true, alpha=0.05
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("ripley-envelope-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")
R = "distance r"
L = "L(r)"
LO = "pointwise low"
HI = "pointwise high"
LO_G = "global low"
HI_G = "global high"
CENTRED = True # L(r) − r: a random pattern is the flat line at 0
d = df.dropna(subset=[R, L]).sort_values(R)
r = d[R].to_numpy(dtype=float)
shift = r if CENTRED else 0.0
fig, ax = plt.subplots(figsize=(8, 4.5))
if LO and HI:
ax.fill_between(r, d[LO] - shift, d[HI] - shift, color=PALETTE[0], alpha=0.16, linewidth=0, label="pointwise envelope")
if LO_G and HI_G:
ax.plot(r, d[HI_G] - shift, color=GREY, linestyle="--", linewidth=1, label="global envelope")
ax.plot(r, d[LO_G] - shift, color=GREY, linestyle="--", linewidth=1)
ax.plot(r, np.zeros_like(r) if CENTRED else r, color=REF, linestyle=":", label="random pattern")
ax.plot(r, d[L] - shift, color=PALETTE[0], linewidth=1.8, label="observed")
ax.set(xlabel=R, ylabel="L(r) − r" if CENTRED else "L(r)")
ax.legend(frameon=False, fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads ripley-envelope-demo.csv · app theme from the optional codesplash helper
# Ripley's L with envelopes — Codesplash Chart Lab (recipe "ripley-envelope")
# controls: centred=true, alpha=0.05
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("ripley-envelope-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")
R = "distance r"
L = "L(r)"
LO = "pointwise low"
HI = "pointwise high"
LO_G = "global low"
HI_G = "global high"
CENTRED = True # L(r) − r: a random pattern is the flat line at 0
d = df.dropna(subset=[R, L]).sort_values(R)
r = d[R].to_numpy(dtype=float)
shift = r if CENTRED else 0.0
fig = go.Figure()
if LO and HI:
fig.add_trace(go.Scatter(x=np.r_[r, r[::-1]], y=np.r_[d[HI] - shift, (d[LO] - shift)[::-1]], fill="toself", mode="none", fillcolor="rgba(120,150,200,0.25)", name="pointwise envelope"))
if LO_G and HI_G:
fig.add_trace(go.Scatter(x=r, y=d[HI_G] - shift, mode="lines", name="global envelope", line=dict(color=GREY, dash="dash", width=1)))
fig.add_trace(go.Scatter(x=r, y=d[LO_G] - shift, mode="lines", showlegend=False, line=dict(color=GREY, dash="dash", width=1)))
fig.add_trace(go.Scatter(x=r, y=np.zeros_like(r) if CENTRED else r, mode="lines", name="random pattern", line=dict(color=REF, dash="dot")))
fig.add_trace(go.Scatter(x=r, y=d[L] - shift, mode="lines", name="observed", line=dict(color=PALETTE[0], width=2)))
fig.update_layout(xaxis_title=R, yaxis_title="L(r) − r" if CENTRED else "L(r)")
fig.show()Needs pandas, numpy, plotly · reads ripley-envelope-demo.csv · app theme from the optional codesplash helper
# Ripley's L with envelopes — Codesplash Chart Lab (recipe "ripley-envelope")
# controls: centred=true, alpha=0.05
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("ripley-envelope-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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
r_col <- "distance r"
l_col <- "L(r)"
lo_col <- "pointwise low"
hi_col <- "pointwise high"
lo_g_col <- "global low"
hi_g_col <- "global high"
centred <- TRUE # L(r) − r: a random pattern is the flat line at 0
d <- df[!is.na(df[[r_col]]) & !is.na(df[[l_col]]), , drop = FALSE]
d <- d[order(d[[r_col]]), , drop = FALSE]
d$rr <- d[[r_col]]
shift <- if (centred) d$rr else 0
d$observed <- d[[l_col]] - shift
d$random <- if (centred) 0 else d$rr
p <- ggplot(d, aes(rr))
if (!is.null(lo_col) && !is.null(hi_col)) {
d$low <- d[[lo_col]] - shift; d$high <- d[[hi_col]] - shift
p <- p + geom_ribbon(data = d, aes(ymin = low, ymax = high), fill = cs_cat[1], alpha = 0.16)
}
if (!is.null(lo_g_col) && !is.null(hi_g_col)) {
d$low_g <- d[[lo_g_col]] - shift; d$high_g <- d[[hi_g_col]] - shift
p <- p + geom_line(data = d, aes(y = low_g), linetype = "dashed", colour = grey_col) + geom_line(data = d, aes(y = high_g), linetype = "dashed", colour = grey_col)
}
p <- p + geom_line(data = d, aes(y = random), linetype = "dotted", colour = ref_col) + geom_line(data = d, aes(y = observed), colour = cs_cat[1], linewidth = 0.9) +
labs(x = r_col, y = if (centred) "L(r) − r" else "L(r)") + theme_cs
print(p)Needs ggplot2 · reads ripley-envelope-demo.csv · app theme from the optional codesplashr helper