Skip to content
svgpreviewneighbor-graph

Neighbour graph

Which regions count as neighbours for a spatial analysis?

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

How to read it

  1. Read each line as a link between neighbouring regions.
  2. Check regions with very few or very many links.
  3. Islands, with no link, need a decision before you test.
  1. Callout 1: A link between two regions.
  2. Callout 2: Many links in a dense area.
  3. Callout 3: Few links at the edge.

Watch out

  • Every spatial test depends on this graph. Try another definition of neighbours to check robustness.

Defaults

Boundaries
US states
Which set of regions to draw and join your data to.
Also: World countries · World countries (detailed) · US counties

Pinned in the code

  • One row per link (region, neighbour); regions match boundaries by id or name like the choropleth.
  • Nodes sit at each region's projected centroid; regions with no links (islands) have no node.
  • Spatial methods build their weights on the host (Data → Map layers → Neighbours) so Python and R use identical neighbours.
  • Projection: Equal Earth for world maps, Albers USA (with Alaska and Hawaii insets) for US layers, a conic equal-area projection centred on the data otherwise — equal-area, so filled areas are not exaggerated toward the poles.
# Neighbour graph — Codesplash Chart Lab (recipe "neighbor-graph")
# controls: boundaries=us-states
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path

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("neighbor-graph-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")
import json, math, os, re, unicodedata

def region_key(s):
    """Ignore case, accents, punctuation and leading zeros (as the app does when matching regions)."""
    if isinstance(s, float) and s.is_integer():
        s = int(s)
    t = "".join(ch for ch in unicodedata.normalize("NFKD", str(s)) if not unicodedata.combining(ch)).strip().lower()
    t = re.sub(r"[\s._-]+", " ", t)
    return str(int(t)) if t.isdigit() else t

def read_boundaries(path):
    """Features of a GeoJSON file as dicts of id, name and geometry."""
    with open(path, encoding="utf-8") as fh:
        fc = json.load(fh)
    out = []
    for i, f in enumerate(fc["features"]):
        props = f.get("properties") or {}
        fid = f.get("id", i + 1)
        out.append({"id": str(fid), "name": str(props.get("name", fid)), "geometry": f.get("geometry")})
    return out

def polygons_of(geometry):
    """Each polygon as its rings (outer first) in longitude and latitude."""
    if not geometry:
        return []
    if geometry["type"] == "Polygon":
        return [geometry["coordinates"]]
    if geometry["type"] == "MultiPolygon":
        return geometry["coordinates"]
    return []

def contiguous(features):
    """Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets)."""
    def inside(f):
        pts = [p for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
        return bool(pts) and -126 < sum(p[0] for p in pts) / len(pts) < -66 and 24 < sum(p[1] for p in pts) / len(pts) < 50
    return [f for f in features if inside(f)]

def match_regions(features, keys):
    """Each key's feature position: by id, else by name."""
    by = {}
    for i, f in enumerate(features):
        by.setdefault(region_key(f["id"]), i)
    for i, f in enumerate(features):
        by.setdefault(region_key(f["name"]), i)
    return [None if k is None or k != k else by.get(region_key(k)) for k in keys]

def make_projection(lons, lats, scope):
    """Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents."""
    span = max(lons) - min(lons)
    if scope == "world" or span > 120:
        def project(lon, lat):
            th = math.asin(math.sqrt(3) / 2 * math.sin(math.radians(lat)))
            t2 = th * th
            t6 = t2 * t2 * t2
            d = 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
            return (2 * math.sqrt(3) * math.radians(lon) * math.cos(th) / d, th * (0.003796 * t6 * t2 + 0.000893 * t6 + -0.081106 * t2 + 1.340264))
        return project
    lat0 = (min(lats) + max(lats)) / 2
    if span < 2:
        return lambda lon, lat: (lon * math.cos(math.radians(lat0)), lat)
    lon0 = -96.0 if scope == "us" else (min(lons) + max(lons)) / 2
    third = (max(lats) - min(lats)) / 3
    p1, p2 = (math.radians(29.5), math.radians(45.5)) if scope == "us" else (math.radians(min(lats) + third), math.radians(max(lats) - third))
    n = (math.sin(p1) + math.sin(p2)) / 2 or 1e-9
    c = math.cos(p1) ** 2 + 2 * n * math.sin(p1)
    def project(lon, lat):
        rho = math.sqrt(max(0.0, c - 2 * n * math.sin(math.radians(lat)))) / n
        theta = n * math.radians(lon - lon0)
        return (rho * math.sin(theta), -rho * math.cos(theta))
    return project

def feature_extent(features):
    pts = [p for f in features for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
    return [p[0] for p in pts], [p[1] for p in pts]

def load_map(path, scope):
    """Features and their projection, or (None, None) when the boundaries file isn't there."""
    if not os.path.exists(path):
        print(f"No boundaries file at {path}: drawing without the map. Point BOUNDARIES at a GeoJSON file for the regions.")
        return None, None
    features = read_boundaries(path)
    if scope == "us":
        features = contiguous(features)
    lons, lats = feature_extent(features)
    return features, make_projection(lons, lats, scope)
def draw_regions(ax, features, project, fill_of, edge, width=0.5):
    """Fill each region; fill_of(position) gives its colour."""
    for i, f in enumerate(features):
        verts, codes = [], []
        for poly in polygons_of(f["geometry"]):
            for ring in poly:
                pts = [project(p[0], p[1]) for p in ring]
                verts += pts + [pts[0]]
                codes += [Path.MOVETO] + [Path.LINETO] * (len(pts) - 1) + [Path.CLOSEPOLY]
        if verts:
            ax.add_patch(PathPatch(Path(verts, codes), facecolor=fill_of(i), edgecolor=edge, linewidth=width))
    ax.set_aspect("equal")
    ax.autoscale_view()
    ax.set_axis_off()
def centroid_of(feature, project):
    """Area-weighted centroid of the feature's largest ring, in projected coordinates."""
    best, best_area = None, -1.0
    for poly in polygons_of(feature["geometry"]):
        pts = [project(p[0], p[1]) for p in poly[0]]
        area = cx = cy = 0.0
        for (x0, y0), (x1, y1) in zip(pts, pts[1:] + pts[:1]):
            cross = x0 * y1 - x1 * y0
            area += cross
            cx += (x0 + x1) * cross
            cy += (y0 + y1) * cross
        if area and abs(area) > best_area:
            best, best_area = (cx / (3 * area), cy / (3 * area)), abs(area)
    return best
FROM = "state"
TO = "neighbour"
BOUNDARIES = "neighbor-graph-boundaries.geojson"  # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
features, project = load_map(BOUNDARIES, "us")
d = df.dropna(subset=[FROM, TO])
fig, ax = plt.subplots(figsize=(8, 5))
if features is None:
    counts = pd.concat([d[FROM], d[TO]]).astype(str).value_counts().sort_values().tail(40)
    ax.barh(counts.index, counts.values, color=PALETTE[0])
    ax.set_xlabel("neighbours")
else:
    draw_regions(ax, features, project, lambda i: GREY + "55", "white")
    centres = [centroid_of(f, project) for f in features]
    used = set()
    for a, b in zip(match_regions(features, d[FROM].tolist()), match_regions(features, d[TO].tolist())):
        if a is None or b is None or centres[a] is None or centres[b] is None:
            continue
        ax.plot([centres[a][0], centres[b][0]], [centres[a][1], centres[b][1]], color=PALETTE[0], linewidth=1, alpha=0.7)
        used |= {a, b}
    ax.scatter([centres[i][0] for i in used], [centres[i][1] for i in used], s=16, color=PALETTE[0], edgecolors="white", linewidths=0.6, zorder=3)
    ax.set_title("Which regions are neighbours")
plt.show()

Needs pandas, numpy, matplotlib · reads neighbor-graph-demo.csv · app theme from the optional codesplash helper