Do neighbors resemble each other?
Test whether a map's pattern is more than chance with Moran's I and Geary's C, and see why your choice of neighbors is part of the question.
What runs in CodeSplash
- STAT248Global Moran I test Runs in CodeSplash
- STAT249Geary C test Runs in CodeSplash
- Global spatial autocorrelation (Moran's I, Geary's C, Getis–Ord G, join counts) Verified in Python and R
You will be able to
- Explain spatial autocorrelation and why a map can't be judged by eye
- Say how spatial weights define the question a global test answers
- Read Moran's I and Geary's C, including which way each one runs
Read first
Your eye finds patterns everywhere
ReadColor any map and you will see clusters, even after shuffling the values at random.
Spatial autocorrelationSpatial autocorrelationNearby places having more similar (or more different) values than chance would give. asks the question properly: do nearby places have more similar values than chance would give?
In this lesson you test that on crime rates across 49 neighborhoods of Columbus, Ohio.
A checkerboard
PredictPredict first
Moran's IMoran's ILike a correlation between each site's value and its neighbors' average; above its expected value of about 0 means like values cluster. is positive when neighbors are alike. Picture a checkerboard: every high square is surrounded by low squares.
What sign does its Moran's I have?
Reveal
Negative. A checkerboard is highly structured, but neighbors are unlike. "No pattern" sits close to zero, at .
Shuffle a map
ExploreTurn up the clustering, guess I from the map, then compare it with what shuffling the same values over the grid produces. Then drag the slider below zero to make a checkerboard.
CExplorable · Moran's I by shuffling the map
How do you know a pattern on a map is more than chance?
Look at the map. What is Moran's I?
Commit your prediction above to see the result
Make your prediction to see the result.
Shuffling keeps the values and removes the geography. That pile of shuffled maps is what the permutation p-value compares your map against.
Moran's I
ReadThe numerator adds up products of deviations between neighbors. When two neighbors are both above the mean, or both below it, the product is positive.
The are spatial weightsSpatial weightsWho counts as whose neighbor, and how much. They define the spatial question a test answers.: zero unless is a neighbor of .
With row-standardized weights, is the slope of the neighbors' average on a site's own value. The Moran scatterplotMoran scatterplotEach site's standardized value against the average of its neighbors; the slope is Moran's I with row-standardized weights. draws exactly that line.
Neighbors are a choice
ReflectQueen contiguity counts regions that share any boundary point, Rook only those sharing an edge, and k nearest the closest sites by distance. Row-standardized weights turn the neighbors into an average.
Each choice asks a slightly different question. Suppose you study shops competing for customers. Would you define neighbors by shared boundaries or by the five nearest shops? Decide before you see any result, and write your reason down.
Read the card
ReadI = 0.50, z = 5.59, p = .002
- I
- 0.5002
- Expected I
- −0.0208
- z
- 5.589
- p
- .002
- Mean neighbors
- 4.816
Plots
View data
| Site | crime (standardized) | Average of neighbors (spatial lag) |
|---|---|---|
| 1 | −1.172 | −0.6289 |
| 2 | −0.9859 | −0.5363 |
| 3 | −0.2719 | −0.3452 |
| 4 | −0.1655 | −0.0291 |
| 5 | 0.9422 | 0.3222 |
| 6 | −0.5472 | 0.3318 |
| 7 | −2.110 | 0.8816 |
| 8 | 0.1991 | 0.3847 |
| 9 | −0.2785 | 0.1098 |
| 10 | −0.0681 | −0.5918 |
| 11 | 1.639 | 0.8894 |
| 12 | 1.303 | 0.4904 |
| 13 | 0.6997 | 0.1791 |
| 14 | 1.325 | 0.4645 |
| 15 | 0.8126 | 0.9043 |
| 16 | 1.190 | 1.041 |
| 17 | 0.1051 | −1.029 |
| 18 | 0.5334 | 0.9693 |
| 19 | 1.171 | 0.6832 |
| 20 | −2.108 | −0.1620 |
| 21 | 0.2986 | 0.5189 |
| 22 | −0.0860 | 0.0468 |
| 23 | −0.9106 | −0.9893 |
| 24 | 0.1914 | 1.194 |
| 25 | 1.580 | 0.8963 |
| 26 | 0.3527 | 0.8152 |
| 27 | 1.067 | −0.1162 |
| 28 | 1.316 | 0.7425 |
| 29 | 1.547 | 1.006 |
| 30 | 2.039 | 0.8118 |
| 31 | −1.054 | −0.9663 |
| 32 | −0.9651 | −1.285 |
| 33 | 0.4130 | 0.1298 |
| 34 | −0.6736 | −0.7845 |
| 35 | 0.2443 | −0.1226 |
| 36 | −1.257 | −0.9887 |
| 37 | 0.4418 | 0.9580 |
| 38 | 1.122 | 0.5147 |
| 39 | −0.9678 | −1.145 |
| 40 | −1.141 | −0.8499 |
| 41 | −0.9797 | −0.8489 |
| 42 | −1.125 | −0.9655 |
| 43 | 0.0927 | 0.0623 |
| 44 | −0.5535 | 0.0373 |
| 45 | −0.3684 | −0.1845 |
| 46 | −1.123 | −1.113 |
| 47 | −0.4412 | −1.060 |
| 48 | −0.5123 | −0.3973 |
| 49 | −0.7601 | −0.4781 |
View data
| Density | Observed | I |
|---|---|---|
| 0.1233 | 0.5002 | −0.2686 |
| 0.1233 | 0.5002 | −0.2523 |
| 0.1233 | 0.5002 | −0.2360 |
| 0.3698 | 0.5002 | −0.2198 |
| 0.4931 | 0.5002 | −0.2035 |
| 0.6164 | 0.5002 | −0.1873 |
| 1.356 | 0.5002 | −0.1710 |
| 1.726 | 0.5002 | −0.1548 |
| 2.466 | 0.5002 | −0.1385 |
| 2.466 | 0.5002 | −0.1223 |
| 2.466 | 0.5002 | −0.1060 |
| 2.959 | 0.5002 | −0.0897 |
| 4.192 | 0.5002 | −0.0735 |
| 3.698 | 0.5002 | −0.0572 |
| 5.671 | 0.5002 | −0.0410 |
| 4.068 | 0.5002 | −0.0247 |
| 3.205 | 0.5002 | −0.0085 |
| 3.082 | 0.5002 | 0.0078 |
| 3.575 | 0.5002 | 0.0240 |
| 2.959 | 0.5002 | 0.0403 |
| 3.082 | 0.5002 | 0.0566 |
| 2.589 | 0.5002 | 0.0728 |
| 1.849 | 0.5002 | 0.0891 |
| 1.233 | 0.5002 | 0.1053 |
| 1.603 | 0.5002 | 0.1216 |
| 1.356 | 0.5002 | 0.1378 |
| 0.8630 | 0.5002 | 0.1541 |
| 0.6164 | 0.5002 | 0.1703 |
| 0.3698 | 0.5002 | 0.1866 |
| 0.2466 | 0.5002 | 0.2029 |
| 0.8630 | 0.5002 | 0.2191 |
| 0.3698 | 0.5002 | 0.2354 |
| 0.3698 | 0.5002 | 0.2516 |
| 0.1233 | 0.5002 | 0.2679 |
| 0 | 0.5002 | 0.2841 |
| 0 | 0.5002 | 0.3004 |
| 0 | 0.5002 | 0.3166 |
| 0.1233 | 0.5002 | 0.3329 |
| 0 | 0.5002 | 0.3492 |
| 0.1233 | 0.5002 | 0.3654 |
Assumptions
- Neighbors chosen for a reason — Neighbors: Queen contiguity, row-standardized (W). The result answers the question for these neighbors; try a second definition as a sensitivity check.
- Values exchangeable under the null — A trend across the map also produces clustering. If the mean drifts across the map, remove the trend first and test the residuals.
- Regions at a meaningful scale — Changing the size or borders of regions can change the result (the modifiable areal unit problem).
- Neighbors: Queen contiguity, row-standardized (W). p from 499 permutations of the values (seed 42); normal approximation with the randomization variance.
The exact R script · R R version 4.5.1 (2025-06-13)
# Global spatial autocorrelation (Moran's I, Geary's C, Getis–Ord G, join counts)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.autocorrelation 1.1.1 · spec 183a17f92b88f80f
# 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.autocorrelation/moran-columbus-queen/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
# Global spatial autocorrelation over the neighbors above (Moran 1950; Geary 1954; Getis & Ord 1992;
# Cliff & Ord 1981). Permutation p-values shuffle the values across sites on the shared random stream.
Y <- "crime"
test <- "moran" # moran | geary | getis_ord | join_count
calibration <- "permutation" # permutation | randomization | normality
alternative <- "greater" # two_sided | greater | less
n_perm <- as.integer(499)
alpha <- 0.05
seed <- 42
n <- nrow(df)
cs_check_rows(n, 4, "A spatial autocorrelation test") # the moments need four sites (registry/errors.yaml)
LABELS <- c(moran = "Moran's I", geary = "Geary's C", getis_ord = "Getis–Ord G", join_count = "Join counts")
SYMBOLS <- c(moran = "I", geary = "C", getis_ord = "G", join_count = "BW")
rows <- list()
if (test == "join_count") {
# Join counts use binary weights: one link is one join.
if (wt$style != "B") {
wt$w <- cs_weights_style(wt$i, wt$j, wt$g, wt$n, "B")
wt$style <- "B"
warnings <- c(warnings, "Join counts use binary weights, so the weights style was set to binary for this test.")
}
vals <- df[[Y]]
if (is.factor(vals)) {
levels <- levels(vals)
codes <- as.integer(vals)
} else {
uniq <- sort(unique(vals))
levels <- if (is.logical(uniq)) ifelse(uniq, "true", "false") else sprintf("%g", as.numeric(uniq))
codes <- match(vals, uniq)
}
if (length(levels) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = Y, min = 2, k = length(levels))
res <- cs_sp_join_counts(wt, codes, if (calibration == "permutation") calibration else "normal", alternative, n_perm, seed)
rows <- res$rows
} else {
if (!is.numeric(df[[Y]])) stop(sprintf("%s needs a numeric variable; %s is not numeric. Use join counts for categories.", LABELS[[test]], Y))
if (test == "getis_ord" && wt$style != "B") {
warnings <- c(warnings, "Getis–Ord G is usually run with binary weights; row-standardized weights change what it measures.")
}
cs_check_not_constant(df[[Y]], Y)
res <- cs_sp_global_test(wt, as.numeric(df[[Y]]), test, calibration, alternative, n_perm, seed)
}
statistic <- res$statistic
expected <- res$expected
variance <- res$variance
z <- res$z
p <- res$p
# %% Assumptions
assumptions <- list(
list(key = "weights_chosen", label = "Neighbors chosen for a reason", status = "info",
detail = sprintf("Neighbors: %s. The result answers the question for these neighbors; try a second definition as a sensitivity check.", neighbours_label)),
list(key = "exchangeable", label = "Values exchangeable under the null", status = "info",
detail = "A trend across the map also produces clustering. If the mean drifts across the map, remove the trend first and test the residuals."),
list(key = "scale", label = "Regions at a meaningful scale", status = "info",
detail = "Changing the size or borders of regions can change the result (the modifiable areal unit problem).")
)
# %% Result
test_label <- LABELS[[test]]
test_symbol <- SYMBOLS[[test]]
clustered <- if (alternative == "two_sided") z > 0 else alternative == "greater"
pattern <- if (clustered) "Like values cluster more than chance alone would explain." else "Like values are kept apart more than chance alone would explain."
verdict <- if (p < alpha) pattern else "The map is compatible with values placed at random across sites."
how <- if (calibration == "permutation") "permutations" else "normal approximation"
summary <- sprintf("%s for %s: %s = %.3f (expected %.3f), z = %.2f, %s (%s). %s", test_label, Y, test_symbol, statistic, expected, z, cs_fmt_p(p), how, verdict)
values <- list(statistic = statistic, expected = expected, variance = variance, z = z, p = p, p_analytic = res$p_analytic,
p_perm = if (calibration == "permutation") res$p_perm else NULL, n = n, links = res$links,
mean_neighbours = res$links / n, islands = n_islands, n_perm = if (calibration == "permutation") n_perm else 0L,
kurtosis = res$kurtosis, missing_share = if (n_input > 0) n_dropped / n_input else 0,
test_label = test_label, test_symbol = test_symbol, pattern = pattern, neighbours_label = neighbours_label)
tables <- list()
if (length(rows)) {
for (row in rows) {
lv <- levels[row$level]
values[[sprintf("bb[%s]", lv)]] <- row$joins
values[[sprintf("bb_expected[%s]", lv)]] <- row$expected
values[[sprintf("bb_z[%s]", lv)]] <- row$z
values[[sprintf("bb_p[%s]", lv)]] <- row$p
}
columns <- list(list(key = "join", label = "Join", type = "string"), list(key = "joins", label = "Joins", type = "number"),
list(key = "expected", label = "Expected", type = "number"), list(key = "variance", label = "Variance", type = "number"),
list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"))
table_rows <- lapply(rows, function(r) list(join = sprintf("%s–%s", levels[r$level], levels[r$level]), joins = r$joins, expected = r$expected,
variance = r$variance, z = r$z, p = r$p))
table_rows[[length(table_rows) + 1L]] <- list(join = "Different categories", joins = statistic, expected = expected, variance = variance, z = z, p = p)
tables[[1]] <- list(key = "joins", title = "Joins between neighboring sites", columns = columns, rows = table_rows)
}
charts <- list()
if (test != "join_count") {
zv <- as.numeric(df[[Y]])
zv <- (zv - mean(zv)) / sqrt(mean((zv - mean(zv))^2))
charts[[length(charts) + 1L]] <- cs_chart("scatter", "moran-scatter", sprintf("Each site against its neighbors: %s", Y), list(
x = cs_col(sprintf("%s (standardized)", Y), zv),
y = cs_col("Average of neighbors (spatial lag)", cs_weights_lag(wt, zv)),
site = cs_col("Site", site)), controls = list(slope = if (test == "moran") statistic else NULL))
}
if (!is.null(res$null)) {
nc <- cs_sp_null_curve(res$null)
charts[[length(charts) + 1L]] <- cs_chart("null", "null-distribution", sprintf("%s under %d shuffles of the values", test_label, n_perm), list(
x = cs_col(test_symbol, nc$x), density = cs_col("Density", nc$density),
observed = cs_col("Observed", rep(statistic, length(nc$x)))))
}
for (key in c("p_perm", "kurtosis")) if (is.null(values[[key]])) values[[key]] <- NA_real_ # only some options produce these
cs_publish(list(
method = "spatial.autocorrelation",
methodVersion = "1.1.1",
title = test_label,
engine = cs_engine_info("stats"),
n = n,
summary = summary,
apa = sprintf("%s = %.2f, z = %.2f, %s", test_symbol, statistic, z, cs_fmt_p(p)),
statistics = list(list(key = "statistic", label = test_symbol, value = statistic), list(key = "expected", label = sprintf("Expected %s", test_symbol), value = expected),
list(key = "z", label = "z", value = z), list(key = "p", label = "p", value = p, format = "p"),
list(key = "mean_neighbours", label = "Mean neighbors", value = res$links / n)),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Neighbors: %s. ", neighbours_label),
if (calibration == "permutation") sprintf("p from %d permutations of the values (seed %d); ", n_perm, seed) else "",
if (calibration != "normality") "normal approximation with the randomization variance." else "normal approximation assuming normal values.")),
values = values,
charts = charts
))
I = 0.50, z = 5.59, p = .002
- I
- 0.5002
- Expected I
- −0.0208
- z
- 5.589
- p
- .002
- Mean neighbors
- 4.816
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). The result answers the question for these neighbors; try a second definition as a sensitivity check.
- Values exchangeable under the null — A trend across the map also produces clustering. If the mean drifts across the map, remove the trend first and test the residuals.
- Regions at a meaningful scale — Changing the size or borders of regions can change the result (the modifiable areal unit problem).
- Neighbors: Queen contiguity, row-standardized (W). p from 499 permutations of the values (seed 42); normal approximation with the randomization variance.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Global spatial autocorrelation (Moran's I, Geary's C, Getis–Ord G, join counts)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.autocorrelation 1.1.1 · spec 183a17f92b88f80f
# 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.autocorrelation/moran-columbus-queen/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
# Global spatial autocorrelation over the neighbors above (Moran 1950; Geary 1954; Getis & Ord 1992;
# Cliff & Ord 1981). Permutation p-values shuffle the values across sites on the shared random stream.
Y = "crime"
test = "moran" # moran | geary | getis_ord | join_count
calibration = "permutation" # permutation | randomization | normality
alternative = "greater" # two_sided | greater | less
n_perm = int(499)
alpha = 0.05
seed = 42
n = len(df)
cs.check_rows(n, 4, "A spatial autocorrelation test") # the moments need four sites (registry/errors.yaml)
LABELS = {"moran": "Moran's I", "geary": "Geary's C", "getis_ord": "Getis–Ord G", "join_count": "Join counts"}
SYMBOLS = {"moran": "I", "geary": "C", "getis_ord": "G", "join_count": "BW"}
rows = []
if test == "join_count":
# Join counts use binary weights: one link is one join.
if wt["style"] != "B":
wt = {**wt, "w": sw.apply_style(wt["i"], wt["j"], wt["g"], wt["n"], "B"), "style": "B"}
warnings.append("Join counts use binary weights, so the weights style was set to binary for this test.")
vals = df[Y]
if isinstance(vals.dtype, pd.CategoricalDtype):
levels = [str(c) for c in vals.cat.categories]
codes = vals.cat.codes.to_numpy()
else:
uniq = np.sort(vals.unique())
levels = [("true" if u else "false") if isinstance(u, (bool, np.bool_)) else f"{float(u):g}" for u in uniq]
codes = np.searchsorted(uniq, vals.to_numpy())
if len(levels) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=Y, min=2, k=len(levels))
res = sp.join_counts(wt, codes, calibration if calibration == "permutation" else "normal", alternative, n_perm, seed)
rows = res["rows"]
else:
if not pd.api.types.is_numeric_dtype(df[Y]) or pd.api.types.is_bool_dtype(df[Y]):
raise ValueError(f"{LABELS[test]} needs a numeric variable; {Y} is not numeric. Use join counts for categories.")
if test == "getis_ord" and wt["style"] != "B":
warnings.append("Getis–Ord G is usually run with binary weights; row-standardized weights change what it measures.")
check_not_constant(df[Y], Y)
res = sp.global_test(wt, df[Y].to_numpy(dtype=float), test, calibration, alternative, n_perm, seed)
statistic, expected, variance, z, p = res["statistic"], res["expected"], res["variance"], res["z"], res["p"]
# %% Assumptions
assumptions = [
{"key": "weights_chosen", "label": "Neighbors chosen for a reason", "status": "info",
"detail": f"Neighbors: {neighbours_label}. The result answers the question for these neighbors; try a second definition as a sensitivity check."},
{"key": "exchangeable", "label": "Values exchangeable under the null", "status": "info",
"detail": "A trend across the map also produces clustering. If the mean drifts across the map, remove the trend first and test the residuals."},
{"key": "scale", "label": "Regions at a meaningful scale", "status": "info",
"detail": "Changing the size or borders of regions can change the result (the modifiable areal unit problem)."},
]
# %% Result
test_label, test_symbol = LABELS[test], SYMBOLS[test]
clustered = (z > 0) if alternative == "two_sided" else (alternative == "greater")
pattern = ("Like values cluster more than chance alone would explain." if clustered
else "Like values are kept apart more than chance alone would explain.")
if p < alpha:
verdict = pattern
else:
verdict = "The map is compatible with values placed at random across sites."
how = "permutations" if calibration == "permutation" else "normal approximation"
summary = f"{test_label} for {Y}: {test_symbol} = {statistic:.3f} (expected {expected:.3f}), z = {z:.2f}, {cs.fmt_p(p)} ({how}). {verdict}"
values = {"statistic": statistic, "expected": expected, "variance": variance, "z": z, "p": p, "p_analytic": res["p_analytic"],
"p_perm": res["p_perm"] if calibration == "permutation" else None, "n": n, "links": res["links"],
"mean_neighbours": res["links"] / n, "islands": n_islands, "n_perm": n_perm if calibration == "permutation" else 0,
"kurtosis": res.get("kurtosis"), "missing_share": n_dropped / n_input if n_input else 0.0,
"test_label": test_label, "test_symbol": test_symbol, "pattern": pattern, "neighbours_label": neighbours_label}
tables = []
if rows:
for row in rows:
lv = levels[row["level"]]
values[f"bb[{lv}]"] = row["joins"]
values[f"bb_expected[{lv}]"] = row["expected"]
values[f"bb_z[{lv}]"] = row["z"]
values[f"bb_p[{lv}]"] = row["p"]
columns = [{"key": "join", "label": "Join", "type": "string"}, {"key": "joins", "label": "Joins", "type": "number"},
{"key": "expected", "label": "Expected", "type": "number"}, {"key": "variance", "label": "Variance", "type": "number"},
{"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}]
table_rows = [{"join": f"{levels[r['level']]}–{levels[r['level']]}", "joins": r["joins"], "expected": r["expected"],
"variance": r["variance"], "z": r["z"], "p": r["p"]} for r in rows]
table_rows.append({"join": "Different categories", "joins": statistic, "expected": expected, "variance": variance, "z": z, "p": p})
tables.append({"key": "joins", "title": "Joins between neighboring sites", "columns": columns, "rows": table_rows})
charts = []
if test != "join_count":
zv = df[Y].to_numpy(dtype=float)
zv = (zv - zv.mean()) / zv.std(ddof=0)
charts.append(cs.chart("scatter", "moran-scatter", f"Each site against its neighbors: {Y}", {
"x": cs.col(f"{Y} (standardized)", zv),
"y": cs.col("Average of neighbors (spatial lag)", sw.weights_lag(wt, zv)),
"site": cs.col("Site", site)}, controls={"slope": statistic if test == "moran" else None}))
if res["null"] is not None:
grid, density = sp.null_curve(res["null"])
charts.append(cs.chart("null", "null-distribution", f"{test_label} under {n_perm} shuffles of the values", {
"x": cs.col(test_symbol, grid), "density": cs.col("Density", density),
"observed": cs.col("Observed", np.full(grid.size, statistic))}))
for key in ["p_perm", "kurtosis"]: # only some options produce these
values.setdefault(key, None)
cs.publish({
"method": "spatial.autocorrelation",
"methodVersion": "1.1.1",
"title": test_label,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{test_symbol} = {statistic:.2f}, z = {z:.2f}, {cs.fmt_p(p)}",
"statistics": [{"key": "statistic", "label": test_symbol, "value": statistic}, {"key": "expected", "label": f"Expected {test_symbol}", "value": expected},
{"key": "z", "label": "z", "value": z}, {"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "mean_neighbours", "label": "Mean neighbors", "value": res["links"] / n}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Neighbors: {neighbours_label}. " + (f"p from {n_perm} permutations of the values (seed {seed}); " if calibration == "permutation" else "")
+ ("normal approximation with the randomization variance." if calibration != "normality" else "normal approximation assuming normal values.")],
"values": values,
"charts": charts,
})
With Queen contiguity, row-standardized (W), Moran's I is 0.50, against −0.021 expected with no pattern.
From 499 shuffles the result is p = .002. That is the smallest p this many shuffles can give: .
This tells you high-crime areas sit near high-crime areas. It doesn't say why.
Geary's C looks at differences
ReadGeary's CGeary's CA ratio from squared differences between neighbors; below 1 means neighbors are alike, above 1 unlike. uses squared differences between neighbors, so it runs the other way:
C near 1 means no pattern, below 1 means neighbors are alike, above 1 means unlike.
For Columbus, C = 0.54, p = .002. Both statistics tell the same story here. Geary's reacts more to sharp differences between particular neighbors, Moran's to the broad pattern.
A map of pure noise
PredictPredict first
A 6 × 6 grid holds 36 values drawn at random, with nothing spatial in them.
What p-value do you expect from Moran's I?
Reveal
I = 0.18, p = .097. On a small grid, noise alone can lift I above zero, and the p-value says this is compatible with no pattern.
Other reference distributions give p = .101 and p = .076. Pick one before you look; they aren't a menu.
Check your understanding
CheckpointCheck yourself
What is the expected Moran's I under no pattern for 49 sites? Use and give three decimals.
Show the answer
Answer: -0.0208333333333333
, a small negative number rather than exactly zero.
Check yourself
A map gives Geary's C well below 1 with a small p-value. What does that suggest?
Show the answer
Answer: a
C compares squared differences between neighbors with the overall spread. Below 1 means neighbors differ less than chance would give. It says nothing about causes.
Check yourself
Two analysts test the same map, one with rook contiguity and one with 5 nearest neighbors, and get different p-values. Which response is right?
Show the answer
Answer: c
The weights say what "nearby" means, so they are part of the question. Choosing them after seeing the p-values undoes the test's calibration.
Do it in CodeSplash
In the appYour table needs a value per region, such as {{value}} by {{region}}, and a map layer whose ids match, or longitude and latitude columns. Set Neighbors and Weights style, then read the Moran scatterplot before the p-value.
This script builds rook neighbors on the 6 × 6 grid and reproduces I = 0.1768.
import numpy as np
import pandas as pd
x = pd.read_csv("sp_grid6.csv")["x"].to_numpy()
m, n = 6, 36
w = np.zeros((n, n))
for i in range(n):
r, c = divmod(i, m)
for a, b in [(r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)]:
if 0 <= a < m and 0 <= b < m:
w[i, a * m + b] = 1
w = w / w.sum(axis=1, keepdims=True) # row-standardize
z = x - x.mean()
print(n / w.sum() * (z @ w @ z) / (z @ z))x <- read.csv("sp_grid6.csv")$x
m <- 6; n <- 36
w <- matrix(0, n, n)
for (i in 0:(n - 1)) {
r <- i %/% m; c <- i %% m
for (d in list(c(-1, 0), c(1, 0), c(0, -1), c(0, 1))) {
a <- r + d[1]; b <- c + d[2]
if (a >= 0 && a < m && b >= 0 && b < m) w[i + 1, a * m + b + 1] <- 1
}
}
w <- w / rowSums(w) # row-standardize
z <- x - mean(x)
n / sum(w) * sum(z * (w %*% z)) / sum(z^2)Recap
Recap- Spatial autocorrelation asks whether nearby values are more alike than chance would give.
- Moran's I is positive when neighbors are alike. Geary's C runs the other way, with 1 as no pattern.
- The neighbors define the question, so choose them first and report them.
- A clustered map is compatible with a shared driver as well as with spillover.
Concepts in this lesson