Generating h3 Hexgrids from GeoDataFrames¶
import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
from geodatasets import get_path
from tobler.area_weighted import area_interpolate
from tobler.util import h3fy
%load_ext watermark
%watermark -v -a "author: eli knaap" -d -u -p tobler,geopandas
Author: author: eli knaap
Last updated: 2026-11-18
Python implementation: CPython
Python version : 3.14.10
IPython version : 9.18.1
tobler : 0.14.1
geopandas: 1.2.0
Note: This notebook relies on functionality from the contextily package that provides convenient basemaps for geospatial plots. Install the package with
pip install contextily
or
conda install contextily -c conda-forge
nyc = gpd.read_file(get_path("geoda.nyc_education"))
Downloading file 'nyc_2000Census.zip' from 'https://geodacenter.github.io/data-and-lab//data/nyc_2000Census.zip' to '/home/runner/.cache/geodatasets'.
Creating Hexgrids with the h3fy function¶
Using the h3fy function from the tobler.util module, we can easily generate a hexgrid covering the face of the NY.
nyc_hex = h3fy(nyc, resolution=8)
fig, axs = plt.subplots(1, 2, figsize=(18, 10))
axs = axs.flatten()
nyc.plot(ax=axs[0], alpha=0.4, linewidth=1.6, edgecolor="white", tiles=True)
nyc_hex.plot(ax=axs[1], alpha=0.4, linewidth=1.6, edgecolor="white", tiles=True)
axs[0].set_title("Original Tract Data")
axs[1].set_title("Hex Grid")
for ax in axs.flat:
ax.axis("off")
By altering the resolution parameter, we can generate grids using hexes of various sizes
nyc_hex_large = h3fy(nyc, resolution=7)
nyc_hex_small = h3fy(nyc, resolution=9)
fig, axs = plt.subplots(1, 2, figsize=(18, 10))
nyc_hex_large.plot(ax=axs[0], alpha=0.4, linewidth=1.6, edgecolor="white", tiles=True)
nyc_hex_small.plot(ax=axs[1], alpha=0.4, linewidth=1.6, edgecolor="white", tiles=True)
for ax in axs.flat:
ax.axis("off")
and by using the clip parameter, we can ensure that the hexgrid is does not extend beyond the borders of the input geodataframe
nyc_hex_clipped = h3fy(nyc, resolution=7, clip=True)
fig, ax = plt.subplots(figsize=(10, 10))
nyc_hex_clipped.plot(ax=ax, alpha=0.4, linewidth=1.6, edgecolor="white", tiles=True)
ax.axis("off")
ax.set_title("h3fy with clip")
Text(0.5, 1.0, 'h3fy with clip')
Notice, though, that we still have some sharp hexagonal edges, meaning the hexagon doesn’t fully cover the original source polygons. To force full coverage, we can use the buffer keyword (or, optionally, both buffer and clip).
nyc_hex_clipped = h3fy(nyc, resolution=7, clip=True, buffer=True)
fig, ax = plt.subplots(figsize=(10, 10))
nyc_hex_clipped.plot(ax=ax, alpha=0.4, linewidth=1.6, edgecolor="white", tiles=True)
ax.axis("off")
ax.set_title("h3fy with buffer & clip")
Text(0.5, 1.0, 'h3fy with buffer & clip')
Interpolating to a hexgrid¶
Thus, in just a few lines of code, we can estimate the value of census variables represented by a regular hexgrid
here, we will estimate the median home value of each hex in the NY using simple areal interpolation
nyc_hex_interpolated = area_interpolate(
source_df=nyc, target_df=nyc_hex, intensive_variables=["PER_BLACK"], fill_nan="mean"
)
fig, axs = plt.subplots(1, 2, figsize=(20, 10))
nyc.plot("PER_BLACK", scheme="quantiles", alpha=0.7, ax=axs[0], tiles=True)
nyc_hex_interpolated.plot(
"PER_BLACK",
scheme="quantiles",
alpha=0.7,
ax=axs[1],
tiles=True,
)
axs[0].set_title("Original Data")
axs[1].set_title("Interpolated Data")
for ax in axs:
ax.axis("off")
plt.suptitle(
r"Spatial Interpolation with the PySAL $\mathtt{tobler}$ package", fontsize=16
)
Text(0.5, 0.98, 'Spatial Interpolation with the PySAL $\\mathtt{tobler}$ package')
Dealing with NaN Values¶
It’s important to understand how and NaN (not-a-number) values (i.e. missing data) in the source dataframe are handled. Introduce some missing values.
nyc.loc[range(0, len(nyc), 25), "PER_BLACK"] = np.nan
nyc.plot("PER_BLACK", missing_kwds={"color": "red"})
<Axes: xlabel='Easting [US survey foot]', ylabel='Northing [US survey foot]'>
fill_nans = [None, 0.0, "mean", "median"]
f, ax = plt.subplots(2, 2, figsize=(12, 12))
ax = ax.flatten()
for i, nan in enumerate(fill_nans):
nyc_hex_interpolated = area_interpolate(
source_df=nyc,
target_df=nyc_hex,
intensive_variables=["PER_BLACK"],
fill_nan=nan,
).plot("PER_BLACK", scheme="quantiles", alpha=0.5, ax=ax[i])
ax[i].set_title(f"fill_nan={nan}")
/home/runner/micromamba/envs/test/lib/python3.14/site-packages/tobler/area_weighted/area_interpolate.py:351: UserWarning: nan values in variable: PER_BLACK, replacing with None
vals = _nan_check(source_df, variable, fill_value=fill_nan)
/home/runner/micromamba/envs/test/lib/python3.14/site-packages/tobler/area_weighted/area_interpolate.py:351: UserWarning: nan values in variable: PER_BLACK, replacing with 0.0
vals = _nan_check(source_df, variable, fill_value=fill_nan)
/home/runner/micromamba/envs/test/lib/python3.14/site-packages/tobler/area_weighted/area_interpolate.py:351: UserWarning: nan values in variable: PER_BLACK, replacing with 0.2803338034790785
vals = _nan_check(source_df, variable, fill_value=fill_nan)
/home/runner/micromamba/envs/test/lib/python3.14/site-packages/tobler/area_weighted/area_interpolate.py:351: UserWarning: nan values in variable: PER_BLACK, replacing with 0.1
vals = _nan_check(source_df, variable, fill_value=fill_nan)
Further, all of these options are still different from dropping any geometries with missing values for the variable being interpolated. In this case, the dropped observations in source are not part of the overlay system so only the overlapping pieces of source and target count toward the total weight applied.
ax = nyc_hex_interpolated = area_interpolate(
source_df=nyc.dropna(subset=["PER_BLACK"]),
target_df=nyc_hex,
intensive_variables=["PER_BLACK"],
fill_nan=nan,
).plot("PER_BLACK", scheme="quantiles", alpha=0.5)
ax.set_title("drop NA prior to interpolation")
ax.axis("off")
(np.float64(903700.4239424965),
np.float64(1075572.2157699093),
np.float64(113343.12145785264),
np.float64(279318.2721226369))
For extensive variables (where target values are a weighted sum), dropping missing observations is functionally equivalent to setting fill_nan=0 and allocate_total=True.
For intensive variables, however, the weighted average provided by each target zone is not “diluted” by missing data. The total weights at the target polygon is the shared area of source and target, not the total area of target.