def quadtree(xy, x0, y0, x1, y1, cap=25, depth=0, out=None): # recursive point quadtree
"""Return the leaf cells (x0, y0, x1, y1, n) of a point quadtree with capacity `cap`."""
out = [] if out is None else out # list of leaf cells
inside = xy[(xy[:, 0] >= x0) & (xy[:, 0] < x1) & (xy[:, 1] >= y0) & (xy[:, 1] < y1)] # points in the cell
if len(inside) <= cap or depth >= 10: # small enough: keep as a leaf
out.append((x0, y0, x1, y1, len(inside))); return out
xm, ym = (x0 + x1) / 2, (y0 + y1) / 2 # cell centre
for a, b, c, d in [(x0, y0, xm, ym), (xm, y0, x1, ym), (x0, ym, xm, y1), (xm, ym, x1, y1)]: # 4 children
quadtree(inside, a, b, c, d, cap, depth + 1, out) # recurse
return out
conus = sites.cx[-125:-66, 24:50].to_crs(5070) # sites in the lower 48 (lon/lat window), in Albers
xy = np.column_stack([conus.geometry.x, conus.geometry.y]) # coordinates
x0, y0, x1, y1 = xy[:, 0].min(), xy[:, 1].min(), xy[:, 0].max() + 1, xy[:, 1].max() + 1 # root cell
cells = quadtree(xy, x0, y0, x1, y1) # build the tree
fig, ax = plt.subplots(figsize=(11, 6)) # one map
states.drop(["02", "15", "72"], errors="ignore").to_crs(5070).boundary.plot(ax=ax, color="0.75", lw=0.4)
ax.scatter(xy[:, 0], xy[:, 1], s=3, color="#d95f02") # the sites
for a, b, c, d, n in cells: # every leaf cell
ax.add_patch(Rectangle((a, b), c - a, d - b, fill=False, ec="#3182bd", lw=0.5))
ax.set_title(f"Quadtree of {len(xy):,} Superfund sites: {len(cells)} leaf cells, at most 25 sites each")
ax.set_xticks([]); ax.set_yticks([]); plt.show() # no ticks, draw