Skip to content
svgmoran-scatter

Moran scatterplot

Do sites resemble their neighbours, and which sites break the pattern?

Demo data · seed 20261101 · 49 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read x as each site's standardized value and y as the average of its neighbours.
  2. Read the slope of the line as Moran's I: steeper means neighbours resemble each other more.
  3. Top right and bottom left hold sites like their neighbours; the other two corners hold outliers.
  1. Callout 1: High-High: high sites among high neighbours.
  2. Callout 2: Low-Low: low sites among low neighbours.
  3. Callout 3: Low-High: a low site among high neighbours.
  4. 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