Skip to content
svgkde-map

Kernel density map

Where are points concentrated, as a smooth surface?

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

How to read it

  1. Read the darkest band as where points are most concentrated.
  2. Read the bands as shares of the map's own peak, so compare shapes between maps and not colours.
  3. Try another bandwidth: a smaller one shows more local detail and a larger one merges clusters.
  1. Callout 1: The peak: the densest area.
  2. Callout 2: A second concentration.
  3. Callout 3: The lowest band: few points.
  4. Callout 4: Legend: bands as a share of the peak.

Watch out

  • Points usually follow where people or stores are. For risk, compare with the population at risk.
  • The surface spreads past the points and over water or borders. It shows concentration, not where things can occur.

Defaults

Outlines
US states
Outlines drawn under the density. Choose the set that covers your points, or none.
Also: None · World countries
Bandwidth multiplier
0.5
1 is Silverman's rule, which blurs separate clusters together; smaller shows more local detail.
Range 0.25 to 3, step 0.25
Contour bands
6
How many density levels to shade between the lowest band and the peak.
Range 3 to 10, step 1

Pinned in the code

  • An isotropic Gaussian kernel on the projected map, so with an equal-area projection each contour's area is true ground area.
  • Bandwidth is Silverman's rule h = σ n^(−1/6), with σ² the average of the two coordinate variances, times the multiplier. The default of 0.5 keeps separate clusters apart, which the rule alone blurs.
  • Colour shows density relative to the map's peak, so maps with different data aren't comparable by colour alone.
  • 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 density surface of raw points mostly shows where people or stores are. For risk, compare with the population at risk.

# Kernel density map — Codesplash Chart Lab (recipe "kde-map")
# controls: basemap=us-states, bandwidth=0.5, bands=6
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path
import matplotlib.colors as mpl_colors

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("kde-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)
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 density_grid(xy, weights, adjust, nx=160):
    """Gaussian kernel density on a grid over the points, as a share of the peak. Silverman: h = σ n^(−1/6)."""
    sw = weights.sum()
    m = (xy * weights[:, None]).sum(axis=0) / sw
    sigma = math.sqrt(((xy - m) ** 2 * weights[:, None]).sum() / (2 * sw))
    h = adjust * sigma * (sw * sw / (weights * weights).sum()) ** (-1 / 6)
    x0, x1 = xy[:, 0].min() - 3 * h, xy[:, 0].max() + 3 * h
    y0, y1 = xy[:, 1].min() - 3 * h, xy[:, 1].max() + 3 * h
    ny = max(2, int(nx * (y1 - y0) / (x1 - x0)))
    gx, gy = np.linspace(x0, x1, nx), np.linspace(y0, y1, ny)
    z = np.exp(-(gx[None, :] - xy[:, 0, None]) ** 2 / (2 * h * h)).T @ (weights[:, None] * np.exp(-(gy[None, :] - xy[:, 1, None]) ** 2 / (2 * h * h)))
    return gx, gy, (z / z.max()).T
LON = "longitude"
LAT = "latitude"
WEIGHT = None
BOUNDARIES = "kde-map-boundaries.geojson"  # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
SCOPE = "us"
DRAW_OUTLINES = True
base, project = load_map(BOUNDARIES, SCOPE) if DRAW_OUTLINES else (None, None)
d = df.dropna(subset=[LON, LAT])
d = d[d[LAT].abs() <= 90]
if project is None:
    project = make_projection(d[LON].tolist(), d[LAT].tolist(), SCOPE)
xy = np.array([project(lon, lat) for lon, lat in zip(d[LON], d[LAT])])
weights = d[WEIGHT].fillna(0).to_numpy(dtype=float) if WEIGHT else np.ones(len(d))
gx, gy, z = density_grid(xy, weights, 0.5)  # 1 is Silverman's rule, which blurs separate clusters together
levels = [(i + 1) / 7 for i in range(6)] + [1.0001]
fig, ax = plt.subplots(figsize=(8, 5))
if base is not None:
    draw_regions(ax, base, project, lambda i: GREY + "55", "white")
cmap = mpl_colors.LinearSegmentedColormap.from_list("seq", [SEQ[0], SEQ[-1]])
ax.contourf(gx, gy, z, levels=levels, cmap=cmap, alpha=0.62)
ax.set_aspect("equal")
ax.set_axis_off()
ax.set_title("Density of points, as a share of the peak")
plt.show()

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