Skip to content

How far does resemblance reach?

Correlograms follow Moran's I outward through neighbors of neighbors, and variograms give the nugget, sill and range of a measured surface.

Advanced ~14 min11 steps

What runs in CodeSplash

You will be able to

  • Read a correlogram by neighbor order
  • Define the nugget, sill and range of a semivariogram
  • Check a variogram's pair counts before trusting its points

Read first

01

Beyond the next door

Read

Moran's I tells you that neighbors are alike. A natural next question: how far does that last?

A spatial correlogramSpatial correlogramMoran's I or Geary's C for neighbors, neighbors of neighbors and so on, showing how far resemblance reaches. repeats Moran's I for neighbors, then neighbors of neighbors, and so on. Those steps are called orders.

02

Follow the signal

Predict

Predict first

Columbus crime has Moran's I of 0.50 for direct neighbors.

The city has a high-crime side and a low-crime side. What happens to I as you go several neighbor orders out?

It stays strongly positiveIt fades, then turns negativeIt stays at zero
Reveal

It fades, then turns negative. Distant areas sit on opposite sides, so they differ. Significant similarity holds through order 2. On a grid of pure noise, the same reach is 0: no order shows significant similarity.

03

Several tests, one chart

Read
Moran's I correlogramRecorded · Python and R agreeRecorded 2026-11-25 · 33 values compared
R

5 neighbor orders, range 2

Moran's I, first order
0.5002
Orders with like values
2

Plots

Moran's I by neighbor order: crimeOver what distances are rows more alike (or less alike) than average?
View data
Neighbor orderAdjusted pLinksMoran's I
11.139e-72360.5002
20.04724160.1449
30.0472486−0.1523
45.839e-6468−0.3153
51.139e-7342−0.4561

Assumptions

  • Neighbors chosen for a reason — Neighbors: Queen 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

OrderLinksMoran's IExpectedzpAdjusted p
12360.5002−0.02085.589< .001< .001
24160.1449−0.02082.263.024.047
3486−0.1523−0.0208−2.018.044.047
4468−0.3153−0.0208−4.759< .001< .001
5342−0.4561−0.0208−5.566< .001< .001
  • Neighbors: Queen contiguity, row-standardized (W). Normal approximation with the randomization variance at each order; p adjusted across orders (holm).
The exact R script · R 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 d825f520949dfa1e
# Dataset: sp_columbus (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_columbus.parquet", col_select = c("crime", "site")))
n_input <- nrow(df)
df[["site"]] <- factor(df[["site"]], levels = sort(unique(df[["site"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("crime", "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("crime", "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-columbus/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 <- "crime"
test <- "moran"  # moran | geary
alternative <- "two_sided"  # two_sided | greater | less
adjust_method <- "holm"  # holm | BH | bonferroni | none
max_lag <- as.integer(5)
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
))
Python

5 neighbor orders, range 2

Moran's I, first order
0.5002
Orders with like values
2

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Neighbors chosen for a reason — Neighbors: Queen 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

OrderLinksMoran's IExpectedzpAdjusted p
12360.5002−0.02085.589< .001< .001
24160.1449−0.02082.263.024.047
3486−0.1523−0.0208−2.018.044.047
4468−0.3153−0.0208−4.759< .001< .001
5342−0.4561−0.0208−5.566< .001< .001
  • Neighbors: Queen contiguity, row-standardized (W). Normal approximation with the randomization variance at each order; p adjusted across orders (holm).
The exact Python script · Python 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 d825f520949dfa1e
# Dataset: sp_columbus (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_columbus.parquet", columns=["crime", "site"])
n_input = len(df)
df["site"] = pd.Categorical(df["site"], categories=sorted(df["site"].dropna().unique()))
df = df.dropna(subset=["crime", "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, ["crime", "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-columbus/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 = "crime"
test = "moran"  # moran | geary
alternative = "two_sided"  # two_sided | greater | less
adjust_method = "holm"  # holm | BH | bonferroni | none
max_lag = int(5)
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,
})

Each order is its own test, so the method applies a correction, Holm by default.

Read the orders from the first outward, and stop where significant positive values end. That gives the reach in neighbor orders, not in miles.

04

The semivariogram

Read

For a variable measured at coordinates, use distance directly. The semivariogramSemivariogramHalf the average squared difference between pairs of sites, by distance. Low at short range when nearby sites resemble each other. is half the average squared difference between pairs a distance hh apart:

γ(h)=12N(h)∑(i,j)∈N(h)(zi−zj)2\gamma(h) = \frac{1}{2N(h)}\sum_{(i,j) \in N(h)} (z_i - z_j)^2

Nearby sites are similar, so γ\gamma starts low. It rises as sites stop resembling each other, then levels off near the overall variance.

05

Which way does it go?

Predict

Predict first

Topsoil zinc was measured at 155 sites along the river Meuse. Zinc comes with flood water, so soil close to the river is rich in it.

How does γ\gamma for log zinc change with distance?

Rises with distanceFalls with distanceStays flat
Reveal

It rises: from 0.13 in the shortest distance class to 0.56 in the longest. Close samples are alike.

06

Nugget, sill and range

Read

A fitted curve gives three numbers:

  • The nuggetNuggetThe semivariance at distance zero, from measurement error and variation closer than your closest pair of sites. is the value at distance zero: measurement error and variation too fine to see. Here 0.062.
  • The sillSillThe level where a semivariogram flattens out, close to the data's total variance. is where the curve levels off: 0.65, next to a sample variance of 0.52.
  • The rangeRange of a semivariogramThe distance past which sites stop resembling each other. Samples further apart than this carry nearly independent information. is the distance past which sites stop resembling each other: about 943 meters.
07

Compare two fits

Reflect

An exponential model on the same soil reports range = 450, which looks far shorter. But its curve only approaches the sill, so the method also gives an effective range: 1,349.

Before comparing models, ask whether you're comparing the same quantity. Which number would you report to someone deciding how far apart to take samples, and why?

08

Check the pair counts

Predict

Predict first

For North Carolina county rates, the first distance class gives γ\gamma = 4.69, far higher than the classes after it, against a variance of 1.47.

Would you report that nearby counties are unusually different?

Yes, neighboring counties differ mostNo, check how many pairs it rests on
Reveal

No. The smallest class holds only 2 pairs, so that point tells you almost nothing. The permutation band shows what shuffled values would give, and the test compares the whole curve with it: here p = .060.

09

Check your understanding

Checkpoint

Check yourself

A variogram has a large nugget compared with its sill. What does that suggest?

Show the answer

Answer: b

The nugget is the value as distance shrinks to zero. A large one means close pairs still differ a lot.

Check yourself

Why does the correlogram correct its p-values across orders?

Show the answer

Answer: b

Testing five orders gives five chances for a false alarm. The correction keeps that under control; it doesn't make the tests independent.

Check yourself

Two pairs of sites fall in the same distance class. Their values differ by 1 and by 3. What is γ\gamma for this class, using 12N∑(zi−zj)2\frac{1}{2N}\sum (z_i - z_j)^2?

Show the answer

Answer: 2.5

12×2(12+32)=10/4=2.5\frac{1}{2 \times 2}(1^2 + 3^2) = 10/4 = 2.5.

Check yourself

Read the Columbus correlogram. Through which neighbor order does significant positive similarity hold?

Show the answer

Answer: 2

It holds through this order, and beyond it the values turn negative. That reach is counted in neighbor steps, so its distance on the ground varies across the map.

Check yourself

A correlogram shows a reach of 2 orders. What can you say?

Show the answer

Answer: b

Orders are steps along the neighbor graph. Use a variogram if you need a reach in units of distance.

Check yourself

A spherical fit reports a range of 900 meters and an exponential fit a range of 450 meters, on the same data. What should you check?

Show the answer

Answer: b

The exponential model's range is a scale parameter. Its effective range, about three times larger, is the number to compare.

10

Do it in CodeSplash

In the app

Use a correlogram when you have regions and neighbors, and a variogram when you have coordinates and a measured value. Log-transform skewed variables, or choose the Cressie–Hawkins (robust) estimator.

This script reproduces the first class, 0.130: all pairs within 100 meters.

Python
import numpy as np
import pandas as pd

d = pd.read_csv("sp_meuse.csv")
xy = d[["x", "y"]].to_numpy()
z = d["log_zinc"].to_numpy()

i, j = np.triu_indices(len(z), 1)
h = np.linalg.norm(xy[i] - xy[j], axis=1)
pairs = h <= 100
print(pairs.sum(), np.mean((z[i][pairs] - z[j][pairs]) ** 2) / 2)
R
d <- read.csv("sp_meuse.csv")
h <- dist(d[, c("x", "y")])
dz <- dist(d$log_zinc)

pairs <- h <= 100
c(sum(pairs), mean(dz[pairs]^2) / 2)
11

Recap

Recap
  • A correlogram follows Moran's I outward by neighbor order, with a correction across orders.
  • A semivariogram shows half the average squared difference by distance.
  • The nugget, sill and range describe its shape; compare effective ranges across models.
  • Check pair counts before you trust a point.