svgpreviewhexbin-map
Hex-bin map
Where are points dense, when there are too many to draw?
How to read it
- Read each hexagon's colour as points inside it.
- Find the darkest hexagons: the densest places.
- Use the legend: the scale is a square root.
- Callout 1: Darkest: the densest area.
- Callout 2: A cluster.
- Callout 3: Legend.
Watch out
- Hexagon size changes the picture; try other radii.
Defaults
- Outlines
- US states
- Which region outlines to draw behind the marks.
- Also: None · World countries
- Hexagon radius (px)
- 10
- The size of each hexagon on the map: larger gives fewer bins and a smoother picture.
- Range 4 to 30, step 1
Pinned in the code
- Hexagons are equal on screen (after projection), so with an equal-area projection each covers the same ground area.
- Colour ∝ √count (or √sum of the weight) so sparse cells stay visible; the legend shows the counts the colours stand for.
- For analysis-grade bins in a dataset, use Prepare → Spatial join / aggregate (host hex bins in Web Mercator metres).
- 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.
# Hex-bin map — Codesplash Chart Lab (recipe "hexbin-map")
# controls: basemap=us-states, radius=10
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("hexbin-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 ramp(t, lo=SEQ[0], hi=SEQ[-1]):
a, b = [np.array([int(x[j:j + 2], 16) for j in (1, 3, 5)]) for x in (lo, hi)]
return "#%02x%02x%02x" % tuple(int(round(x)) for x in a + (b - a) * float(t))
def hexbin_points(xy, weights, r):
"""Pointy-top hexagon bins of radius r (d3-hexbin's layout): centres and summed weights."""
dx, dy = r * 2 * math.sin(math.pi / 3), r * 1.5
bins = {}
for (x, y), w in zip(xy, weights):
py = y / dy
pj = round(py)
px = x / dx - (pj & 1) / 2
pi_ = round(px)
py1 = py - pj
if abs(py1) * 3 > 1:
px1 = px - pi_
pi2 = pi_ + (-1 if px < pi_ else 1) / 2
pj2 = pj + (-1 if py < pj else 1)
if px1 * px1 + py1 * py1 > (px - pi2) ** 2 + (py - pj2) ** 2:
pi_ = pi2 + (1 if pj & 1 else -1) / 2
pj = pj2
key = (pi_, pj)
cx, cy = (pi_ + (pj & 1) / 2) * dx, pj * dy
bins[key] = (cx, cy, bins.get(key, (0, 0, 0))[2] + w)
return np.array(list(bins.values()))
def hexagon(cx, cy, r):
return [(cx + r * math.sin(k * math.pi / 3), cy - r * math.cos(k * math.pi / 3)) for k in range(6)]
LON = "longitude"
LAT = "latitude"
WEIGHT = None
BOUNDARIES = "hexbin-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].to_numpy(dtype=float) if WEIGHT else np.ones(len(d))
r = (xy[:, 0].max() - xy[:, 0].min()) * 0.0161290322581 # the control's radius at a 640 px chart
bins = hexbin_points(xy, weights, r)
peak = max(1.0, bins[:, 2].max())
fig, ax = plt.subplots(figsize=(8, 5))
if base is not None:
draw_regions(ax, base, project, lambda i: GREY + "55", "white")
for cx, cy, v in bins: # colour ∝ √value, so sparse cells stay visible
ax.fill(*zip(*hexagon(cx, cy, r * 0.96)), color=ramp(0.15 + 0.85 * math.sqrt(max(v, 0)) / math.sqrt(peak)), linewidth=0)
ax.set_aspect("equal")
ax.set_axis_off()
ax.set_title(f"{WEIGHT or 'points'} per hexagon (colour on a square-root scale)")
plt.show()Needs pandas, numpy, matplotlib · reads hexbin-map-demo.csv · app theme from the optional codesplash helper
# Hex-bin map — Codesplash Chart Lab (recipe "hexbin-map")
# controls: basemap=us-states, radius=10
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("hexbin-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 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))
def hexbin_points(xy, weights, r):
"""Pointy-top hexagon bins of radius r (d3-hexbin's layout): centres and summed weights."""
dx, dy = r * 2 * math.sin(math.pi / 3), r * 1.5
bins = {}
for (x, y), w in zip(xy, weights):
py = y / dy
pj = round(py)
px = x / dx - (pj & 1) / 2
pi_ = round(px)
py1 = py - pj
if abs(py1) * 3 > 1:
px1 = px - pi_
pi2 = pi_ + (-1 if px < pi_ else 1) / 2
pj2 = pj + (-1 if py < pj else 1)
if px1 * px1 + py1 * py1 > (px - pi2) ** 2 + (py - pj2) ** 2:
pi_ = pi2 + (1 if pj & 1 else -1) / 2
pj = pj2
key = (pi_, pj)
cx, cy = (pi_ + (pj & 1) / 2) * dx, pj * dy
bins[key] = (cx, cy, bins.get(key, (0, 0, 0))[2] + w)
return np.array(list(bins.values()))
def hexagon(cx, cy, r):
return [(cx + r * math.sin(k * math.pi / 3), cy - r * math.cos(k * math.pi / 3)) for k in range(6)]
LON = "longitude"
LAT = "latitude"
WEIGHT = None
BOUNDARIES = "hexbin-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].to_numpy(dtype=float) if WEIGHT else np.ones(len(d))
r = (xy[:, 0].max() - xy[:, 0].min()) * 0.0161290322581 # the control's radius at a 640 px chart
bins = hexbin_points(xy, weights, r)
peak = max(1.0, bins[:, 2].max())
traces = region_traces(base, project, lambda i: GREY, lambda col: "outlines", "white") if base is not None else []
xs, ys = [], []
for cx, cy, _v in bins:
pts = hexagon(cx, cy, r * 0.96)
xs += [p[0] for p in pts] + [pts[0][0], None]
ys += [p[1] for p in pts] + [pts[0][1], None]
traces.append(go.Scatter(x=bins[:, 0], y=bins[:, 1], mode="markers", name=WEIGHT or "points", text=[f"{v:.4g}" for v in bins[:, 2]], hoverinfo="text",
marker=dict(symbol="hexagon", size=14, color=np.sqrt(np.maximum(bins[:, 2], 0)) / math.sqrt(peak), colorscale=[[0, SEQ[0]], [1, SEQ[-1]]], showscale=False)))
fig = go.Figure(traces)
fig.update_layout(title=f"{WEIGHT or 'points'} per hexagon (colour on a square-root scale)", **MAP_LAYOUT)
fig.show()Needs pandas, numpy, plotly · reads hexbin-map-demo.csv · app theme from the optional codesplash helper
# Hex-bin map — Codesplash Chart Lab (recipe "hexbin-map")
# controls: basemap=us-states, radius=10
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("hexbin-map-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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")
hexbin_points <- function(x, y, w, r) {
# Pointy-top hexagon bins of radius r (d3-hexbin's layout): centres and summed weights.
dx <- r * 2 * sin(pi / 3); dy <- r * 1.5
py <- y / dy; pj <- round(py)
px <- x / dx - (pj %% 2) / 2; pi_ <- round(px)
py1 <- py - pj
for (i in which(abs(py1) * 3 > 1)) {
px1 <- px[i] - pi_[i]
pi2 <- pi_[i] + (if (px[i] < pi_[i]) -1 else 1) / 2
pj2 <- pj[i] + (if (py[i] < pj[i]) -1 else 1)
if (px1^2 + py1[i]^2 > (px[i] - pi2)^2 + (py[i] - pj2)^2) {
pi_[i] <- pi2 + (if (pj[i] %% 2 == 1) 1 else -1) / 2
pj[i] <- pj2
}
}
key <- paste(pi_, pj)
out <- stats::aggregate(w, list(key = key), sum)
first <- match(out$key, key)
data.frame(cx = (pi_[first] + (pj[first] %% 2) / 2) * dx, cy = pj[first] * dy, value = out$x)
}
lon_col <- "longitude"
lat_col <- "latitude"
weight_col <- NULL
boundaries_file <- "hexbin-map-boundaries.geojson" # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
scope <- "us"
base <- if (TRUE) load_map(boundaries_file, scope) else NULL
d <- df[!is.na(df[[lon_col]]) & !is.na(df[[lat_col]]) & abs(df[[lat_col]]) <= 90, , drop = FALSE]
project <- if (!is.null(base)) base$project else make_projection(d[[lon_col]], d[[lat_col]], scope)
d <- cbind(d, project(d[[lon_col]], d[[lat_col]]))
outlines <- if (!is.null(base)) geom_polygon(data = base$rings, aes(x, y, group = piece, subgroup = ring), fill = grey_col, colour = "white", linewidth = 0.2, alpha = 0.35) else NULL
w <- if (!is.null(weight_col)) d[[weight_col]] else rep(1, nrow(d))
r <- diff(range(d$x)) * 0.0161290322581 # the control's radius at a 640 px chart
bins <- hexbin_points(d$x, d$y, w, r)
angles <- (0:5) * pi / 3
hexes <- do.call(rbind, lapply(seq_len(nrow(bins)), function(i) data.frame(id = i, value = bins$value[i], hx = bins$cx[i] + 0.96 * r * sin(angles), hy = bins$cy[i] - 0.96 * r * cos(angles))))
peak <- max(1, bins$value)
p <- ggplot() + outlines + geom_polygon(data = hexes, aes(hx, hy, group = id, fill = sqrt(pmax(value, 0)) / sqrt(peak))) +
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[length(seq_ramp)], name = if (is.null(weight_col)) "points (√ scale)" else paste(weight_col, "(√ scale)")) + coord_equal() + theme_cs + theme_map
print(p)Needs ggplot2 · reads hexbin-map-demo.csv · app theme from the optional codesplashr helper