CSpatial · spatial.correlogram
Spatial correlogram (Moran's I or Geary's C by neighbor order)
How far does the resemblance between sites reach across the map?
Repeats Moran's I or Geary's C for neighbors, neighbors of neighbors and so on, to show how quickly similarity fades with distance along the neighbor graph. Tests at several orders are corrected for multiplicity.
A real result
Example “Moran guide grid”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
4 neighbor orders, range 0
- Moran's I, first order
- 0.1768
- Orders with like values
- 0
Plots
View data
| Neighbor order | Adjusted p | Links | Moran's I |
|---|---|---|---|
| 1 | 0.3892 | 120 | 0.1768 |
| 2 | 1 | 196 | 0.0087 |
| 3 | 1 | 232 | −0.0116 |
| 4 | 1 | 232 | −0.0088 |
Assumptions
- Neighbors chosen for a reason — Neighbors: Rook contiguity, row-standardized (W). Orders count steps along this graph, not physical distance.
- Same pattern across the map — A trend across the map keeps the correlogram positive at short orders and negative at long ones. Remove the trend first if you see that shape.
Moran's I by neighbor order
| Order | Links | Moran's I | Expected | z | p | Adjusted p |
|---|---|---|---|---|---|---|
| 1 | 120 | 0.1768 | −0.0286 | 1.658 | .097 | .389 |
| 2 | 196 | 0.0087 | −0.0286 | 0.3940 | .694 | 1.000 |
| 3 | 232 | −0.0116 | −0.0286 | 0.2013 | .840 | 1.000 |
| 4 | 232 | −0.0088 | −0.0286 | 0.2378 | .812 | 1.000 |
- Neighbors: Rook contiguity, row-standardized (W). Normal approximation with the randomization variance at each order; p adjusted across orders (holm).
4 neighbor orders, range 0
- Moran's I, first order
- 0.1768
- Orders with like values
- 0
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Neighbors chosen for a reason — Neighbors: Rook contiguity, row-standardized (W). Orders count steps along this graph, not physical distance.
- Same pattern across the map — A trend across the map keeps the correlogram positive at short orders and negative at long ones. Remove the trend first if you see that shape.
Moran's I by neighbor order
| Order | Links | Moran's I | Expected | z | p | Adjusted p |
|---|---|---|---|---|---|---|
| 1 | 120 | 0.1768 | −0.0286 | 1.658 | .097 | .389 |
| 2 | 196 | 0.0087 | −0.0286 | 0.3940 | .694 | 1.000 |
| 3 | 232 | −0.0116 | −0.0286 | 0.2013 | .840 | 1.000 |
| 4 | 232 | −0.0088 | −0.0286 | 0.2378 | .812 | 1.000 |
- Neighbors: Rook contiguity, row-standardized (W). Normal approximation with the randomization variance at each order; p adjusted across orders (holm).
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Moran guide gridsp_grid6 · region: site · y: x
- Moran columbussp_columbus · region: site · y: crime
- Geary ncsp_nc_sids · region: fips · y: rate
- Degenerate constantsp_grid6 · region: site · y: x
- Degenerate n3sp_grid6 · region: site · y: x
In the guides
Where it sits in the decision guides
- Continuous–continuous: Pearson / Spearman / Kendall · Statistics Guide · C — Test association
What you need
- Variablenumeric · 1 column
- What you measured at each site: a rate, amount or score.
- Regioncategorical / numeric · 0–1 column
- One row per region, with the map layer's feature id (FIPS code, ISO code …). Needs a map layer.
- Longitudenumeric · 0–1 column
- Degrees east, when sites are points instead of regions of a map layer.
- Latitudenumeric · 0–1 column
- Degrees north, when sites are points instead of regions of a map layer.
Choices you make
hypothesis
- Statisticdefault moran
The statistic computed at each neighbor order.
- Moran's I(default) — Positive at orders where neighbors are alike; expected value is about 0.
- Geary's C — Below 1 at orders where neighbors are alike; expected value is 1.
- Alternativedefault two_sided
The pattern you expect at each order.
- Either direction(default) — Like or unlike values at each order.
- Like values — Positive autocorrelation at each order.
- Unlike values — Negative autocorrelation at each order.
- Multiple-testing correctiondefault holm
Several orders means several tests.
- Holm(default) — Controls the chance of any false order; the usual choice for a correlogram.
- False discovery rate (Benjamini–Hochberg) — Controls the share of false orders among those flagged.
- Bonferroni — The strictest correction.
- No correction — Raw p-values at each order.
- Significance leveldefault 0.05
Level used in the table and narrative.
options
- Neighbor ordersdefault 5
How many steps along the neighbor graph: 2 means neighbors of neighbors.
- Map layerdefault —
Regions to build neighbors from; rows match features through the Region role. Leave empty to use longitude and latitude columns.
- Neighborsdefault queen
Which sites count as neighbors. The host builds the weights once; Python and R read the same file.
- Queen contiguity(default) — Regions sharing any boundary point.
- Rook contiguity — Regions sharing a boundary edge (two or more points).
- k nearest — Each site's k closest sites (not symmetric).
- Distance band — All sites within a distance.
- Inverse distance — Closer sites weigh more: 1 / distance^power.
- Kernel — Weights fall smoothly to zero at a bandwidth.
- Neighbors (k)default 4
How many nearest sites count as neighbors (k nearest), or set the adaptive kernel bandwidth.
- Distance (km)default —
Distance band, inverse-distance cut-off or fixed kernel bandwidth, in km between longitude/latitude sites.
- Distance powerdefault 1
Inverse-distance decay: 1 = 1/d, 2 = 1/d².
- Kerneldefault triangular
Shape of the decay inside the bandwidth.
- Triangular(default) — 1 − d/h.
- Uniform — Equal weight inside the bandwidth.
- Quadratic (Epanechnikov) — ¾ (1 − (d/h)²).
- Quartic (biweight) — 15/16 (1 − (d/h)²)².
- Gaussian — Normal density of d/h, cut at the bandwidth.
- Adaptive bandwidthdefault off
Each site's bandwidth reaches its k-th nearest site, so dense areas get narrower kernels.
- Weights styledefault W
How weights are scaled (spdep styles). Row-standardized is the usual choice for Moran's I and spatial lags.
- Row-standardized (W)(default) — Each site's weights sum to 1: spatial lags are neighbor averages.
- Binary (B) — 1 for neighbors (raw weights for inverse distance and kernels).
- Global (C) — All weights sum to the number of sites.
- Sum to one (U) — All weights together sum to 1.
- Variance-stabilizing (S) — Tiefelsdorf's style: between W and C for uneven neighbor counts.
- Min–max — Divided by the smaller of the largest row and column sums.
- Sites with no neighborsdefault keep
Islands (e.g. Hawaii with contiguity) have no neighbors; keep them, stop, or join each to its nearest site.
- Keep (no neighbors)(default) — Tests exclude or zero their lag (spdep zero.policy).
- Stop and list them — Fail so you can choose a different neighborhood.
- Join to the nearest site — Add a link to the closest site in both directions.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Neighbors chosen for a reason
Orders count steps along the neighbor graph you chose, not physical distance.
Same pattern across the map
A trend across the map keeps the correlogram positive at short orders and negative at long ones.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_lags
- How many independent units the analysis used; it sets precision and power.
- links
- Who counts as whose neighbor, and how much. They define the spatial question a test answers.
- range_lag
- Moran's I or Geary's C for neighbors, neighbors of neighbors and so on, showing how far resemblance reaches.
- first_statistic
- Moran's I or Geary's C for neighbors, neighbors of neighbors and so on, showing how far resemblance reaches.
- islands
- Sites with no neighbors under the chosen rule, such as Hawaii with contiguity.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
- test_label
- Name of the spatial statistic used, e.g. Moran's I, Geary's C or the Clark–Evans test.
Per group, level or term: lag_stat[<lag>], lag_z[<lag>], lag_p[<lag>], lag_p_adj[<lag>], lag_links[<lag>]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, jsonlite, codesplashr.
Default traps between the two languages
- Neighbor orders are shortest paths along the host's neighbor graph, the same as spdep::nblag; Moran's I and its moments at each order match spdep::sp.correlogram to 1e-9.
The exact script CodeSplash ran for example “Moran guide grid” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Spatial correlogram (Moran's I or Geary's C by neighbor order)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.correlogram 1.0.3 · spec 9462fe8a3b9d5f9a
# Dataset: sp_grid6 (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import spatial as sp
from codesplash.stats import spatial_weights as sw
# %% Data
df = pd.read_parquet("tests/parity/fixtures/sp_grid6.parquet", columns=["x", "site"])
n_input = len(df)
df["site"] = pd.Categorical(df["site"], categories=sorted(df["site"].dropna().unique()))
df = df.dropna(subset=["x", "site"]) # listwise deletion over the analysis columns
df["site"] = df["site"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["x", "site"]) # infinite values stop the run (registry/errors.yaml)
# %% Spatial weights
# The host builds the neighbors once from the options you chose and writes them next to this run, so Python
# and R read the same file. Rows with missing values leave the weights too; the style is re-applied.
wt = sw.load_weights("target/academy-parity/run-8142/spatial.correlogram/moran-guide-grid/out-python")
if len(df) != wt["n"]:
wt = sw.weights_subset(wt, df.index.to_numpy())
n_islands = len(wt["islands"])
neighbours_label = wt["description"] or "the chosen neighbors"
if n_islands:
warnings.append(f"{n_islands} site(s) have no neighbors; their spatial lag is 0 and local tests skip them.")
site = df["site"].astype(str).to_numpy()
# %% Test
# The statistic at each neighbor order: shortest paths along the neighbor graph, each order's links re-weighted
# in the run's style (Cliff & Ord 1981; Oden 1984).
Y = "x"
test = "moran" # moran | geary
alternative = "two_sided" # two_sided | greater | less
adjust_method = "holm" # holm | BH | bonferroni | none
max_lag = int(4)
alpha = 0.05
n = len(df)
cs.check_rows(n, 4, "A spatial correlogram") # each order's test needs four sites (registry/errors.yaml)
check_not_constant(df[Y], Y)
res = sp.correlogram(wt, df[Y].to_numpy(dtype=float), test, max_lag, alternative, adjust_method)
rows = res["rows"]
if not rows:
cs.cs_error("CS_E_UNDEFINED", what="A spatial correlogram", reason="fewer than 4 sites have neighbors")
test_label = "Moran's I" if test == "moran" else "Geary's C"
# %% Assumptions
assumptions = [
{"key": "weights_chosen", "label": "Neighbors chosen for a reason", "status": "info",
"detail": f"Neighbors: {neighbours_label}. Orders count steps along this graph, not physical distance."},
{"key": "stationary", "label": "Same pattern across the map", "status": "info",
"detail": "A trend across the map keeps the correlogram positive at short orders and negative at long ones. Remove the trend first if you see that shape."},
]
# %% Result
like = lambda row: (row["statistic"] > row["expected"]) if test == "moran" else (row["statistic"] < row["expected"])
range_lag = 0
for row in rows:
if row["p_adj"] < alpha and like(row):
range_lag = row["lag"]
else:
break
values = {"n": n, "n_lags": res["n_lags"], "links": int(wt["i"].size), "range_lag": range_lag, "first_statistic": rows[0]["statistic"], "islands": n_islands,
"missing_share": n_dropped / n_input if n_input else 0.0, "test_label": test_label}
for row in rows:
values[f"lag_stat[{row['lag']}]"] = row["statistic"]
values[f"lag_z[{row['lag']}]"] = row["z"]
values[f"lag_p[{row['lag']}]"] = row["p"]
values[f"lag_p_adj[{row['lag']}]"] = row["p_adj"]
values[f"lag_links[{row['lag']}]"] = row["links"]
summary = f"{test_label} correlogram for {Y} over {res['n_lags']} neighbor orders: " + (
f"like values reach {range_lag} neighbor order(s)." if range_lag else "no neighbor order stands out after the correction.")
tables = [{"key": "orders", "title": f"{test_label} by neighbor order", "columns": [
{"key": "lag", "label": "Order", "type": "integer"}, {"key": "links", "label": "Links", "type": "integer"},
{"key": "statistic", "label": test_label, "type": "number"}, {"key": "expected", "label": "Expected", "type": "number"},
{"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}, {"key": "p_adj", "label": "Adjusted p", "type": "pvalue"}],
"rows": [{k: r[k] for k in ("lag", "links", "statistic", "expected", "z", "p", "p_adj")} for r in rows]}]
charts = [cs.chart("correlogram", "mantel-correlogram", f"{test_label} by neighbor order: {Y}", {
"mid": cs.col("Neighbor order", np.array([r["lag"] for r in rows], dtype=float)),
"r": cs.col(test_label, np.array([r["statistic"] for r in rows])),
"p": cs.col("Adjusted p", np.array([r["p_adj"] for r in rows])),
"pairs": cs.col("Links", np.array([r["links"] for r in rows], dtype=float))}, controls={"alpha": alpha})]
cs.publish({
"method": "spatial.correlogram",
"methodVersion": "1.0.3",
"title": f"{test_label} correlogram",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{res['n_lags']} neighbor orders, range {range_lag}",
"statistics": [{"key": "first_statistic", "label": f"{test_label}, first order", "value": rows[0]["statistic"]},
{"key": "range_lag", "label": "Orders with like values", "value": range_lag}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Neighbors: {neighbours_label}. Normal approximation with the randomization variance at each order; p adjusted across orders ({adjust_method})."],
"values": values,
"charts": charts,
})
The exact script CodeSplash ran for example “Moran guide grid” · R version 4.5.1 (2025-06-13)
# Spatial correlogram (Moran's I or Geary's C by neighbor order)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.correlogram 1.0.3 · spec 9462fe8a3b9d5f9a
# Dataset: sp_grid6 (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/sp_grid6.parquet", col_select = c("x", "site")))
n_input <- nrow(df)
df[["site"]] <- factor(df[["site"]], levels = sort(unique(df[["site"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("x", "site")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("x", "site")) # infinite values stop the run (registry/errors.yaml)
# %% Spatial weights
# The host builds the neighbors once from the options you chose and writes them next to this run, so R and
# Python read the same file. Rows with missing values leave the weights too; the style is re-applied.
wt <- cs_load_weights("target/academy-parity/run-8142/spatial.correlogram/moran-guide-grid/out-r")
if (nrow(df) != wt$n) wt <- cs_weights_subset(wt, as.integer(rownames(df)))
n_islands <- length(wt$islands)
neighbours_label <- if (nzchar(wt$description)) wt$description else "the chosen neighbors"
if (n_islands > 0) {
warnings <- c(warnings, sprintf("%d site(s) have no neighbors; their spatial lag is 0 and local tests skip them.", n_islands))
}
site <- as.character(df[["site"]])
# %% Test
# The statistic at each neighbor order: shortest paths along the neighbor graph, each order's links re-weighted
# in the run's style (Cliff & Ord 1981; Oden 1984).
Y <- "x"
test <- "moran" # moran | geary
alternative <- "two_sided" # two_sided | greater | less
adjust_method <- "holm" # holm | BH | bonferroni | none
max_lag <- as.integer(4)
alpha <- 0.05
n <- nrow(df)
cs_check_rows(n, 4, "A spatial correlogram") # each order's test needs four sites (registry/errors.yaml)
cs_check_not_constant(df[[Y]], Y)
res <- cs_sp_correlogram(wt, as.numeric(df[[Y]]), test, max_lag, alternative, adjust_method)
rows <- res$rows
if (!length(rows)) cs_error("CS_E_UNDEFINED", what = "A spatial correlogram", reason = "fewer than 4 sites have neighbors")
test_label <- if (test == "moran") "Moran's I" else "Geary's C"
# %% Assumptions
assumptions <- list(
list(key = "weights_chosen", label = "Neighbors chosen for a reason", status = "info",
detail = sprintf("Neighbors: %s. Orders count steps along this graph, not physical distance.", neighbours_label)),
list(key = "stationary", label = "Same pattern across the map", status = "info",
detail = "A trend across the map keeps the correlogram positive at short orders and negative at long ones. Remove the trend first if you see that shape.")
)
# %% Result
like <- function(row) if (test == "moran") row$statistic > row$expected else row$statistic < row$expected
range_lag <- 0L
for (row in rows) {
if (row$p_adj < alpha && like(row)) range_lag <- row$lag else break
}
values <- list(n = n, n_lags = res$n_lags, links = length(wt$i), range_lag = range_lag, first_statistic = rows[[1]]$statistic, islands = n_islands,
missing_share = if (n_input > 0) n_dropped / n_input else 0, test_label = test_label)
for (row in rows) {
values[[sprintf("lag_stat[%d]", row$lag)]] <- row$statistic
values[[sprintf("lag_z[%d]", row$lag)]] <- row$z
values[[sprintf("lag_p[%d]", row$lag)]] <- row$p
values[[sprintf("lag_p_adj[%d]", row$lag)]] <- row$p_adj
values[[sprintf("lag_links[%d]", row$lag)]] <- row$links
}
summary <- paste0(sprintf("%s correlogram for %s over %d neighbor orders: ", test_label, Y, res$n_lags),
if (range_lag > 0) sprintf("like values reach %d neighbor order(s).", range_lag) else "no neighbor order stands out after the correction.")
pick <- function(key) vapply(rows, function(r) as.numeric(r[[key]]), 0)
tables <- list(list(key = "orders", title = sprintf("%s by neighbor order", test_label), columns = list(
list(key = "lag", label = "Order", type = "integer"), list(key = "links", label = "Links", type = "integer"),
list(key = "statistic", label = test_label, type = "number"), list(key = "expected", label = "Expected", type = "number"),
list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"), list(key = "p_adj", label = "Adjusted p", type = "pvalue")),
rows = lapply(rows, function(r) r[c("lag", "links", "statistic", "expected", "z", "p", "p_adj")])))
charts <- list(cs_chart("correlogram", "mantel-correlogram", sprintf("%s by neighbor order: %s", test_label, Y), list(
mid = cs_col("Neighbor order", pick("lag")), r = cs_col(test_label, pick("statistic")),
p = cs_col("Adjusted p", pick("p_adj")), pairs = cs_col("Links", pick("links"))), controls = list(alpha = alpha)))
cs_publish(list(
method = "spatial.correlogram",
methodVersion = "1.0.3",
title = sprintf("%s correlogram", test_label),
engine = cs_engine_info("stats"),
n = n,
summary = summary,
apa = sprintf("%d neighbor orders, range %d", res$n_lags, range_lag),
statistics = list(list(key = "first_statistic", label = sprintf("%s, first order", test_label), value = rows[[1]]$statistic),
list(key = "range_lag", label = "Orders with like values", value = range_lag)),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Neighbors: %s. Normal approximation with the randomization variance at each order; p adjusted across orders (%s).", neighbours_label, adjust_method)),
values = values,
charts = charts
))
Sources
- Cliff, A. D., & Ord, J. K. (1981). Spatial Processes: Models and Applications. Pion.
- Oden, N. L. (1984). Assessing the significance of a spatial correlogram. Geographical Analysis, 16, 1–16.
From the CodeSplash method registry · spatial.correlogram v1.0.3.