svgmoran-scatter
Moran scatterplot
Do sites resemble their neighbours, and which sites break the pattern?
How to read it
- Read x as each site's standardized value and y as the average of its neighbours.
- Read the slope of the line as Moran's I: steeper means neighbours resemble each other more.
- Top right and bottom left hold sites like their neighbours; the other two corners hold outliers.
- Callout 1: High-High: high sites among high neighbours.
- Callout 2: Low-Low: low sites among low neighbours.
- Callout 3: Low-High: a low site among high neighbours.
- Callout 4: The slope: Moran's I with row-standardised weights.
Watch out
- One or two far-out sites can set the slope. Look for them before you trust the number.
- A trend across the map also tilts this line, and it isn't local resemblance. Remove the trend and look again.
Defaults
No settings: the chart draws one way.
Pinned in the code
- With row-standardised weights the least-squares slope of the spatial lag on the centred value is Moran's I; when the analysis reports I, the line has that slope.
- Quadrant lines cross at the means. Top right and bottom left are sites like their neighbours; the other two quadrants are sites unlike them.
- Both axes span the same range, so a steeper line means neighbours resemble each site more.
# Moran scatterplot — Codesplash Chart Lab (recipe "moran-scatter")
# controls: defaults
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("moran-scatter-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")
ORDER = ["High-High", "Low-Low", "High-Low", "Low-High", "Hot spot", "Cold spot", "High variability", "Not significant"]
def blend(a, b, t):
"""Blend two #rrggbb colours in sRGB."""
x, y = [np.array([int(c[j:j + 2], 16) for j in (1, 3, 5)]) for c in (a, b)]
return "#%02x%02x%02x" % tuple(int(round(v)) for v in x + (y - x) * t)
# High values on the warm end of the ramp, as on most published LISA maps; outliers are paler.
PATTERN_COLOURS = {"High-High": DIV[0], "Hot spot": DIV[0], "High-Low": blend(DIV[1], DIV[0], 0.45), "Low-Low": DIV[-1], "Cold spot": DIV[-1],
"Low-High": blend(DIV[1], DIV[-1], 0.45), "High variability": PALETTE[3], "Not significant": GREY}
def moran_line(x, y, given=None):
"""Least-squares line through the means, or the analysis's Moran's I as the slope."""
cx, cy = x.mean(), y.mean()
slope = float(given) if given is not None else float(((x - cx) * (y - cy)).sum() / ((x - cx) ** 2).sum())
return cx, cy, slope
X = "rate (standardized)"
Y = "average of neighbours"
SITE = "state"
LABEL = "pattern"
d = df.dropna(subset=[X, Y])
x, y = d[X].to_numpy(dtype=float), d[Y].to_numpy(dtype=float)
cx, cy, slope = moran_line(x, y, None)
lim = 1.1 * max(np.abs(x - cx).max(), np.abs(y - cy).max())
fig, ax = plt.subplots(figsize=(7, 6))
ax.axvline(cx, color=REF, linestyle="--", linewidth=1)
ax.axhline(cy, color=REF, linestyle="--", linewidth=1)
if LABEL:
labels = d[LABEL].astype(str).to_numpy()
for p in [q for q in ORDER if q in labels] + sorted(set(labels) - set(ORDER)):
mask = labels == p
ax.scatter(x[mask], y[mask], s=30, color=REF if p == "Not significant" else PATTERN_COLOURS.get(p, GREY), label=f"{p} ({mask.sum()})")
ax.legend(frameon=False, fontsize=8)
else:
ax.scatter(x, y, s=30, alpha=0.65, color=PALETTE[0])
line_x = np.array([cx - lim, cx + lim])
ax.plot(line_x, cy + slope * (line_x - cx), linewidth=1.5, color=REF)
if SITE: # Name the flagged sites or, without patterns, the five furthest from the centre.
named = np.flatnonzero(d[LABEL].astype(str) != "Not significant") if LABEL else np.argsort(np.hypot(x - cx, y - cy))[-5:]
for i in named:
ax.annotate(str(d[SITE].iloc[i]), (x[i], y[i]), xytext=(4, 3), textcoords="offset points", fontsize=7, color=REF)
ax.set(xlim=(cx - lim, cx + lim), ylim=(cy - lim, cy + lim), xlabel=X, ylabel=Y, title=f"Slope {slope:.3f}")
for (tx, ty, ha, va, name) in [(1, 1, "right", "top", "High-High"), (0, 1, "left", "top", "Low-High"), (0, 0, "left", "bottom", "Low-Low"), (1, 0, "right", "bottom", "High-Low")]:
ax.text(tx, ty, name, transform=ax.transAxes, ha=ha, va=va, fontsize=8, color=REF)
plt.show()Needs pandas, numpy, matplotlib · reads moran-scatter-demo.csv · app theme from the optional codesplash helper
# Moran scatterplot — Codesplash Chart Lab (recipe "moran-scatter")
# controls: defaults
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("moran-scatter-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")
ORDER = ["High-High", "Low-Low", "High-Low", "Low-High", "Hot spot", "Cold spot", "High variability", "Not significant"]
def blend(a, b, t):
"""Blend two #rrggbb colours in sRGB."""
x, y = [np.array([int(c[j:j + 2], 16) for j in (1, 3, 5)]) for c in (a, b)]
return "#%02x%02x%02x" % tuple(int(round(v)) for v in x + (y - x) * t)
# High values on the warm end of the ramp, as on most published LISA maps; outliers are paler.
PATTERN_COLOURS = {"High-High": DIV[0], "Hot spot": DIV[0], "High-Low": blend(DIV[1], DIV[0], 0.45), "Low-Low": DIV[-1], "Cold spot": DIV[-1],
"Low-High": blend(DIV[1], DIV[-1], 0.45), "High variability": PALETTE[3], "Not significant": GREY}
def moran_line(x, y, given=None):
"""Least-squares line through the means, or the analysis's Moran's I as the slope."""
cx, cy = x.mean(), y.mean()
slope = float(given) if given is not None else float(((x - cx) * (y - cy)).sum() / ((x - cx) ** 2).sum())
return cx, cy, slope
X = "rate (standardized)"
Y = "average of neighbours"
SITE = "state"
LABEL = "pattern"
d = df.dropna(subset=[X, Y])
x, y = d[X].to_numpy(dtype=float), d[Y].to_numpy(dtype=float)
cx, cy, slope = moran_line(x, y, None)
lim = 1.1 * max(np.abs(x - cx).max(), np.abs(y - cy).max())
sites = d[SITE].astype(str).to_numpy() if SITE else np.array([""] * len(d))
fig = go.Figure()
if LABEL:
labels = d[LABEL].astype(str).to_numpy()
for p in [q for q in ORDER if q in labels] + sorted(set(labels) - set(ORDER)):
mask = labels == p
fig.add_trace(go.Scatter(x=x[mask], y=y[mask], mode="markers", name=f"{p} ({mask.sum()})", text=sites[mask], marker=dict(size=7, color=REF if p == "Not significant" else PATTERN_COLOURS.get(p, GREY))))
else:
fig.add_trace(go.Scatter(x=x, y=y, mode="markers", name="sites", text=sites, marker=dict(size=7, opacity=0.65, color=PALETTE[0])))
fig.add_trace(go.Scatter(x=[cx - lim, cx + lim], y=[cy - lim * slope, cy + lim * slope], mode="lines", name=f"slope {slope:.3f}", line=dict(color=REF, width=1.5)))
fig.add_vline(x=cx, line_dash="dash", line_color=REF)
fig.add_hline(y=cy, line_dash="dash", line_color=REF)
fig.update_layout(xaxis_title=X, yaxis_title=Y, xaxis_range=[cx - lim, cx + lim], yaxis_range=[cy - lim, cy + lim])
fig.show()Needs pandas, numpy, plotly · reads moran-scatter-demo.csv · app theme from the optional codesplash helper
# Moran scatterplot — Codesplash Chart Lab (recipe "moran-scatter")
# controls: defaults
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("moran-scatter-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["state"]] <- factor(df[["state"]])
df[["pattern"]] <- factor(df[["pattern"]])
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
pattern_order <- c("High-High", "Low-Low", "High-Low", "Low-High", "Hot spot", "Cold spot", "High variability", "Not significant")
blend <- function(a, b, t) grDevices::rgb(grDevices::colorRamp(c(a, b))(t), maxColorValue = 255)
# High values on the warm end of the ramp, as on most published LISA maps; outliers are paler.
pattern_colours <- c("High-High" = div_ramp[1], "Hot spot" = div_ramp[1], "High-Low" = blend(div_ramp[2], div_ramp[1], 0.45), "Low-Low" = div_ramp[3], "Cold spot" = div_ramp[3],
"Low-High" = blend(div_ramp[2], div_ramp[3], 0.45), "High variability" = cs_cat[4], "Not significant" = grey_col)
x_col <- "rate (standardized)"
y_col <- "average of neighbours"
site_col <- "state"
label_col <- "pattern"
d <- df[!is.na(df[[x_col]]) & !is.na(df[[y_col]]), , drop = FALSE]
x <- d[[x_col]]; y <- d[[y_col]]
cx <- mean(x); cy <- mean(y)
given <- NULL # the analysis's Moran's I, when it reports one
slope <- if (is.null(given)) sum((x - cx) * (y - cy)) / sum((x - cx)^2) else given
lim <- 1.1 * max(abs(x - cx), abs(y - cy))
quadrants <- data.frame(tx = c(cx + lim, cx - lim, cx - lim, cx + lim), ty = c(cy + lim, cy + lim, cy - lim, cy - lim), hj = c(1, 0, 0, 1), vj = c(1, 1, 0, 0), name = c("High-High", "Low-High", "Low-Low", "High-Low"))
p <- ggplot(d, aes(.data[[x_col]], .data[[y_col]])) + geom_vline(xintercept = cx, linetype = "dashed", colour = ref_col) + geom_hline(yintercept = cy, linetype = "dashed", colour = ref_col) +
geom_text(data = quadrants, aes(tx, ty, label = name, hjust = hj, vjust = vj), size = 2.8, colour = ref_col, inherit.aes = FALSE)
if (!is.null(label_col)) {
d$pattern <- as.character(d[[label_col]])
shown <- pattern_colours; shown["Not significant"] <- ref_col
p <- p + geom_point(data = d, aes(colour = pattern), size = 2) + scale_colour_manual(values = shown, name = NULL)
} else {
p <- p + geom_point(colour = cs_cat[1], alpha = 0.65, size = 2)
}
if (!is.null(site_col)) { # Name the flagged sites or, without patterns, the five furthest from the centre.
named <- if (!is.null(label_col)) which(as.character(d[[label_col]]) != "Not significant") else utils::tail(order(sqrt((x - cx)^2 + (y - cy)^2)), 5)
p <- p + geom_text(data = d[named, , drop = FALSE], aes(label = .data[[site_col]]), size = 2.4, hjust = -0.15, vjust = -0.3, colour = ref_col)
}
p <- p + geom_abline(intercept = cy - slope * cx, slope = slope, colour = ref_col, linewidth = 0.7) + coord_cartesian(xlim = c(cx - lim, cx + lim), ylim = c(cy - lim, cy + lim)) +
labs(x = x_col, y = y_col, title = sprintf("Slope %.3f", slope)) + theme_cs
print(p)Needs ggplot2 · reads moran-scatter-demo.csv · app theme from the optional codesplashr helper