svglisa-map
Local Moran cluster map (LISA)
Where are clusters of like values, and where are spatial outliers?
How to read it
- Read High-High and Low-Low as clusters: a site and its neighbours are alike.
- Read High-Low and Low-High as spatial outliers: a site unlike its neighbours.
- Grey sites did not pass the adjusted significance level; the faintest have no data.
- Callout 1: A High-High cluster: high values among high neighbours.
- Callout 2: A Low-Low cluster.
- Callout 3: Not significant after the correction.
- Callout 4: Legend, with the number of sites in each pattern.
Watch out
- Local tests share neighbours, so they are dependent. Treat flagged sites as leads to look into, not as discoveries.
- Change the neighbours or the regions and clusters can move: try another definition before you report one.
Defaults
- Boundaries
- US states
- Used only when the result names no map layer.
- Also: World countries · World countries (detailed) · US counties
Pinned in the code
- The first word is the site's own value and the second the average of its neighbours, each relative to the mean: High-Low is a high site among low neighbours.
- Only sites that pass the adjusted significance level take a pattern; the correction is chosen in the analysis (Benjamini–Hochberg by default).
- Local tests share neighbours, so they are dependent: read flagged sites as leads to investigate, not as discoveries.
- The site's region comes from the map layer the analysis used; sites with no matching feature are counted under the map, and regions without a site stay faint.
- 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.
Use with care
A cluster map shows where a statistic stands out under the neighbours you chose. It does not explain why, and changing the neighbours or the regions can move it.
# Local Moran cluster map (LISA) — Codesplash Chart Lab (recipe "lisa-map")
# 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("lisa-map-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)
# A site's pattern comes from the analysis: only sites past the adjusted significance level take one.
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()
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}
SITE = "state"
VALUE = "rate (simulated)"
LABEL = "pattern"
STAT = "local Moran's I"
P_ADJ = "adjusted p"
LON = None
LAT = None
BOUNDARIES = "lisa-map-boundaries.geojson" # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
d = df.dropna(subset=[SITE, LABEL])
labels = d[LABEL].astype(str).tolist()
present = [p for p in ORDER if p in labels] + sorted(set(labels) - set(ORDER))
features, project = (None, None) if LON and LAT else load_map(BOUNDARIES, "us")
label_at = {}
if features is not None:
for fi, lab in zip(match_regions(features, d[SITE].tolist()), labels):
if fi is not None:
label_at[fi] = lab
NO_DATA = blend(GREY, "#ffffff", 0.6)
# The flagged sites with their local statistic and adjusted p, which the map's colours can't show.
flagged = d[d[LABEL].astype(str) != "Not significant"][[k for k in (SITE, VALUE, STAT, P_ADJ, LABEL) if k]]
print((flagged.sort_values(P_ADJ) if P_ADJ else flagged).to_string(index=False))
fig, ax = plt.subplots(figsize=(8, 5))
handles = [PathPatch(Path([(0, 0), (1, 0), (1, 1), (0, 0)]), facecolor=PATTERN_COLOURS.get(p, GREY), label=f"{p} ({labels.count(p)})") for p in present]
if LON and LAT:
pts = d.dropna(subset=[LON, LAT])
proj = make_projection(pts[LON].tolist(), pts[LAT].tolist(), "other")
xy = np.array([proj(a, b) for a, b in zip(pts[LON], pts[LAT])])
ax.scatter(xy[:, 0], xy[:, 1], s=36, c=[PATTERN_COLOURS.get(str(v), GREY) for v in pts[LABEL]], edgecolors="white", linewidths=0.5)
ax.set_aspect("equal")
ax.set_axis_off()
elif features is None:
v = d[VALUE].to_numpy(dtype=float)
order = np.argsort(v)[-40:]
ax.barh(d[SITE].astype(str).to_numpy()[order], v[order], color=[PATTERN_COLOURS.get(labels[i], GREY) for i in order])
ax.set_xlabel(VALUE)
else:
draw_regions(ax, features, project, lambda i: PATTERN_COLOURS.get(label_at[i], GREY) if i in label_at else NO_DATA, "white")
ax.legend(handles=handles, frameon=False, loc="lower left", fontsize=8, ncol=2)
ax.set_title(f"Local spatial patterns of {VALUE}")
plt.show()Needs pandas, numpy, matplotlib · reads lisa-map-demo.csv · app theme from the optional codesplash helper
# Local Moran cluster map (LISA) — Codesplash Chart Lab (recipe "lisa-map")
# controls: boundaries=us-states
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("lisa-map-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)
# A site's pattern comes from the analysis: only sites past the adjusted significance level take one.
def region_traces(features, project, fill_of, name_of, edge, width=0.5):
"""One filled trace per colour; fill_of(position) gives the colour and name_of(colour) its legend entry."""
groups = {}
for i, f in enumerate(features):
xs, ys = groups.setdefault(fill_of(i), ([], []))
for poly in polygons_of(f["geometry"]):
for ring in poly:
pts = [project(p[0], p[1]) for p in ring]
xs += [p[0] for p in pts] + [pts[0][0], None]
ys += [p[1] for p in pts] + [pts[0][1], None]
return [go.Scatter(x=xs, y=ys, mode="lines", fill="toself", fillcolor=colour, line=dict(color=edge, width=width), hoverinfo="name", name=name_of(colour)) for colour, (xs, ys) in groups.items()]
MAP_LAYOUT = dict(xaxis=dict(visible=False, scaleanchor="y"), yaxis=dict(visible=False))
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}
SITE = "state"
VALUE = "rate (simulated)"
LABEL = "pattern"
STAT = "local Moran's I"
P_ADJ = "adjusted p"
LON = None
LAT = None
BOUNDARIES = "lisa-map-boundaries.geojson" # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
d = df.dropna(subset=[SITE, LABEL])
labels = d[LABEL].astype(str).tolist()
present = [p for p in ORDER if p in labels] + sorted(set(labels) - set(ORDER))
features, project = (None, None) if LON and LAT else load_map(BOUNDARIES, "us")
label_at = {}
if features is not None:
for fi, lab in zip(match_regions(features, d[SITE].tolist()), labels):
if fi is not None:
label_at[fi] = lab
NO_DATA = blend(GREY, "#ffffff", 0.6)
# The flagged sites with their local statistic and adjusted p, which the map's colours can't show.
flagged = d[d[LABEL].astype(str) != "Not significant"][[k for k in (SITE, VALUE, STAT, P_ADJ, LABEL) if k]]
print((flagged.sort_values(P_ADJ) if P_ADJ else flagged).to_string(index=False))
if LON and LAT:
pts = d.dropna(subset=[LON, LAT])
proj = make_projection(pts[LON].tolist(), pts[LAT].tolist(), "other")
xy = np.array([proj(a, b) for a, b in zip(pts[LON], pts[LAT])])
lab = pts[LABEL].astype(str).to_numpy()
traces = [go.Scatter(x=xy[lab == p, 0], y=xy[lab == p, 1], mode="markers", name=f"{p} ({labels.count(p)})", text=pts[SITE].astype(str).to_numpy()[lab == p], hoverinfo="text+name", marker=dict(size=9, color=PATTERN_COLOURS.get(p, GREY))) for p in present]
fig = go.Figure(traces)
fig.update_layout(**MAP_LAYOUT)
elif features is None:
v = d[VALUE].to_numpy(dtype=float)
order = np.argsort(v)[-40:]
fig = go.Figure(go.Bar(x=v[order], y=d[SITE].astype(str).to_numpy()[order], orientation="h", marker_color=[PATTERN_COLOURS.get(labels[i], GREY) for i in order]))
fig.update_layout(xaxis_title=VALUE)
else:
names = {PATTERN_COLOURS.get(p, GREY): f"{p} ({labels.count(p)})" for p in present}
fig = go.Figure(region_traces(features, project, lambda i: PATTERN_COLOURS.get(label_at[i], GREY) if i in label_at else NO_DATA, lambda col: names.get(col, "No data"), "white"))
fig.update_layout(**MAP_LAYOUT)
fig.update_layout(title=f"Local spatial patterns of {VALUE}")
fig.show()Needs pandas, numpy, plotly · reads lisa-map-demo.csv · app theme from the optional codesplash helper
# Local Moran cluster map (LISA) — Codesplash Chart Lab (recipe "lisa-map")
# controls: boundaries=us-states
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("lisa-map-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
region_key <- function(s) {
# Ignore case, accents, punctuation and leading zeros (as the app does when matching regions).
t <- tolower(trimws(iconv(as.character(s), to = "ASCII//TRANSLIT", sub = "")))
t <- gsub("[[:space:]._-]+", " ", t)
ifelse(grepl("^[0-9]+$", t), sub("^0+(?=[0-9])", "", t, perl = TRUE), t)
}
read_boundaries <- function(path) {
fc <- jsonlite::read_json(path, simplifyVector = FALSE)
lapply(seq_along(fc$features), function(i) {
f <- fc$features[[i]]
fid <- if (is.null(f$id)) i else f$id
list(id = as.character(fid), name = as.character(if (is.null(f$properties$name)) fid else f$properties$name), geometry = f$geometry)
})
}
ring_table <- function(ring) data.frame(lon = vapply(ring, function(p) as.numeric(p[[1]]), 0), lat = vapply(ring, function(p) as.numeric(p[[2]]), 0))
polygons_of <- function(geometry) {
# Each polygon as its rings (outer first) in longitude and latitude.
if (is.null(geometry)) return(list())
if (geometry$type == "Polygon") return(list(geometry$coordinates))
if (geometry$type == "MultiPolygon") return(geometry$coordinates)
list()
}
feature_rings <- function(features) {
# One row per vertex: feature position, polygon and ring.
parts <- list()
for (i in seq_along(features)) {
polys <- polygons_of(features[[i]]$geometry)
for (p in seq_along(polys)) for (r in seq_along(polys[[p]])) {
tab <- ring_table(polys[[p]][[r]])
if (!nrow(tab)) next
tab$feature <- i; tab$piece <- paste(i, p); tab$ring <- paste(i, p, r)
parts[[length(parts) + 1]] <- tab
}
}
do.call(rbind, parts)
}
contiguous <- function(features) {
# Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets).
keep <- vapply(features, function(f) {
polys <- polygons_of(f$geometry)
pts <- do.call(rbind, lapply(polys, function(p) do.call(rbind, lapply(p, ring_table))))
!is.null(pts) && nrow(pts) > 0 && mean(pts$lon) > -126 && mean(pts$lon) < -66 && mean(pts$lat) > 24 && mean(pts$lat) < 50
}, TRUE)
features[keep]
}
match_regions <- function(features, keys) {
# Each key's feature position: by id, else by name.
ids <- region_key(vapply(features, function(f) f$id, ""))
nms <- region_key(vapply(features, function(f) f$name, ""))
k <- region_key(keys)
hit <- match(k, ids)
ifelse(is.na(hit), match(k, nms), hit)
}
make_projection <- function(lons, lats, scope) {
# Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents.
span <- max(lons) - min(lons)
rad <- pi / 180
if (scope == "world" || span > 120) {
return(function(lon, lat) {
th <- asin(sqrt(3) / 2 * sin(lat * rad)); t2 <- th^2; t6 <- t2^3
d <- 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
data.frame(x = 2 * sqrt(3) * lon * rad * cos(th) / d, y = th * (0.003796 * t6 * t2 + 0.000893 * t6 - 0.081106 * t2 + 1.340264))
})
}
lat0 <- (min(lats) + max(lats)) / 2
if (span < 2) return(function(lon, lat) data.frame(x = lon * cos(lat0 * rad), y = lat))
lon0 <- if (scope == "us") -96 else (min(lons) + max(lons)) / 2
third <- (max(lats) - min(lats)) / 3
p1 <- rad * (if (scope == "us") 29.5 else min(lats) + third)
p2 <- rad * (if (scope == "us") 45.5 else max(lats) - third)
n <- (sin(p1) + sin(p2)) / 2
if (n == 0) n <- 1e-9
cc <- cos(p1)^2 + 2 * n * sin(p1)
function(lon, lat) {
rho <- sqrt(pmax(0, cc - 2 * n * sin(lat * rad))) / n
theta <- n * (lon - lon0) * rad
data.frame(x = rho * sin(theta), y = -rho * cos(theta))
}
}
load_map <- function(path, scope) {
# Features, rings and their projection, or NULL when the boundaries file isn't there.
if (!file.exists(path)) {
message("No boundaries file at ", path, ": drawing without the map. Point boundaries_file at a GeoJSON file for the regions.")
return(NULL)
}
features <- read_boundaries(path)
if (scope == "us") features <- contiguous(features)
rings <- feature_rings(features)
project <- make_projection(rings$lon, rings$lat, scope)
rings <- cbind(rings, project(rings$lon, rings$lat))
list(features = features, rings = rings, project = project)
}
theme_map <- theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), legend.position = "bottom")
# A site's pattern comes from the analysis: only sites past the adjusted significance level take one.
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)
site_col <- "state"
value_col <- "rate (simulated)"
label_col <- "pattern"
stat_col <- "local Moran's I"
p_adj_col <- "adjusted p"
lon_col <- NULL
lat_col <- NULL
boundaries_file <- "lisa-map-boundaries.geojson" # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
d <- df[!is.na(df[[site_col]]) & !is.na(df[[label_col]]), , drop = FALSE]
d$pattern <- as.character(d[[label_col]])
# The flagged sites with their local statistic and adjusted p, which the map's colours can't show.
flagged <- d[d$pattern != "Not significant", c(site_col, value_col, stat_col, p_adj_col, "pattern"), drop = FALSE]
print(if (is.null(p_adj_col)) flagged else flagged[order(flagged[[p_adj_col]]), , drop = FALSE], row.names = FALSE)
present <- c(intersect(pattern_order, d$pattern), sort(setdiff(d$pattern, pattern_order)))
counts <- vapply(present, function(l) sum(d$pattern == l), 0)
legend_labels <- stats::setNames(paste0(present, " (", counts, ")"), present)
fills <- c(pattern_colours, stats::setNames(rep(grey_col, length(setdiff(present, names(pattern_colours)))), setdiff(present, names(pattern_colours))))
m <- if (is.null(lon_col) || is.null(lat_col)) load_map(boundaries_file, "us") else NULL
if (!is.null(lon_col) && !is.null(lat_col)) {
pts <- d[!is.na(d[[lon_col]]) & !is.na(d[[lat_col]]), , drop = FALSE]
pts <- cbind(pts, make_projection(pts[[lon_col]], pts[[lat_col]], "other")(pts[[lon_col]], pts[[lat_col]]))
p <- ggplot(pts, aes(x, y, fill = pattern)) + geom_point(shape = 21, size = 3, colour = "white") + coord_equal() + theme_cs + theme_map
} else if (is.null(m)) {
d <- utils::tail(d[order(d[[value_col]]), , drop = FALSE], 40)
d$site_label <- factor(as.character(d[[site_col]]), levels = as.character(d[[site_col]]))
p <- ggplot(d, aes(.data[[value_col]], site_label, fill = pattern)) + geom_col() + labs(x = value_col, y = NULL) + theme_cs + theme(legend.position = "bottom")
} else {
fi <- match_regions(m$features, d[[site_col]])
label_at <- rep(NA_character_, length(m$features))
label_at[fi[!is.na(fi)]] <- d$pattern[!is.na(fi)]
m$rings$pattern <- label_at[m$rings$feature]
p <- ggplot(m$rings, aes(x, y, group = piece, subgroup = ring, fill = pattern)) + geom_polygon(colour = "white", linewidth = 0.2) + coord_equal() + theme_cs + theme_map
}
p <- p + scale_fill_manual(values = fills, breaks = present, labels = legend_labels, name = NULL, na.value = blend(grey_col, "#ffffff", 0.6)) + labs(title = paste("Local spatial patterns of", value_col))
print(p)Needs ggplot2 · reads lisa-map-demo.csv · app theme from the optional codesplashr helper