To make a hexagon map in Python, convert each latitude and longitude to an H3 cell with h3.latlng_to_cell(lat, lng, resolution), group by that cell, and draw each cell's outline as a polygon. H3 is a global grid of hexagons with a fixed set of resolutions, so counting points per cell is a plain groupby on a string column, with no spatial join. The hexagons then go into GeoPandas, which plots them as a choropleth.
This post uses h3 4.5.1 (the version 4 API, with latlng_to_cell and cell_to_boundary; version 3 used geo_to_h3 and h3_to_geo_boundary), GeoPandas 1.2 and contextily 1.7.1 for the basemap. Install them with pip install h3 geopandas contextily matplotlib. The basemap is drawn the way Add a Basemap to a Map in Python with contextily describes, with tiles from the US Geological Survey.
Quick Example
The data is 6,000 simulated ride pickups in Chicago: five busy neighborhoods plus a thin scatter across the city (seeded, so you get the same map). Each pickup also has a fare, used later.
import contextily as ctx
import geopandas as gpd
import h3
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from shapely.geometry import Polygon
rng = np.random.default_rng(31)
hubs = pd.DataFrame({ # name, center, spread (degrees) and share of pickups
"lat": [41.8820, 41.8920, 41.9088, 41.9484, 41.7943],
"lon": [-87.6278, -87.6340, -87.6796, -87.6553, -87.5907],
"spread": [0.0060, 0.0050, 0.0070, 0.0060, 0.0070],
"share": [0.30, 0.18, 0.16, 0.14, 0.10],
}, index=["Loop", "River North", "Wicker Park", "Wrigleyville", "Hyde Park"])
n_hub, n_all = 5100, 900
pick = rng.choice(len(hubs), size=n_hub, p=hubs["share"] / hubs["share"].sum())
lat = np.r_[hubs["lat"].to_numpy()[pick] + rng.normal(0, 1, n_hub) * hubs["spread"].to_numpy()[pick],
rng.uniform(41.78, 41.98, n_all)]
lon = np.r_[hubs["lon"].to_numpy()[pick] + rng.normal(0, 1, n_hub) * hubs["spread"].to_numpy()[pick],
rng.uniform(-87.74, -87.58, n_all)]
km_from_loop = np.hypot((lat - 41.882) * 111, (lon + 87.6278) * 83)
pickups = pd.DataFrame({"lat": lat, "lon": lon,
"fare": (6 + 1.1 * km_from_loop + rng.gamma(2, 2, len(lat))).round(2)})
pickups["cell"] = [h3.latlng_to_cell(la, lo, 8) for la, lo in zip(pickups["lat"], pickups["lon"])]
def hex_grid(table):
"""GeoDataFrame of hexagons from a table indexed by H3 cell id."""
outlines = [Polygon([(lng, lat) for lat, lng in h3.cell_to_boundary(cell)]) for cell in table.index]
return gpd.GeoDataFrame(table, geometry=outlines, crs="EPSG:4326")
counts = pickups.groupby("cell").size().rename("pickups").to_frame()
hexes = hex_grid(counts).to_crs(epsg=3857)
ax = hexes.plot(column="pickups", cmap="magma_r", alpha=0.8, edgecolor="white", linewidth=0.5,
legend=True, legend_kwds={"label": "Pickups per hexagon", "shrink": 0.6}, figsize=(8, 8))
ctx.add_basemap(ax, source=ctx.providers.USGS.USTopo)
ax.set_axis_off()
plt.show()

Everything unusual is in four lines. latlng_to_cell(lat, lng, 8) returns a 15-character string such as 882664c1a9fffff, which identifies one hexagon. groupby("cell").size() counts the pickups per hexagon. cell_to_boundary() returns the six corners as (lat, lng) pairs, so the comprehension flips them to (lng, lat), the order Shapely and GeoPandas expect. Forgetting that swap puts the hexagons in the wrong place (somewhere in Antarctica for these coordinates).
The map shows 6,000 pickups in 381 hexagons, and the busiest hexagon has 581 of them. A map of raw points would hide that, because dots pile up on top of each other near the Loop.
What do the H3 resolutions mean?
The last argument of latlng_to_cell() is the resolution, from 0 (continent-sized) to 15 (about a square meter). Each step up divides the area of a hexagon by about 7. Resolution 8, used above, is a hexagon with a 0.53 km edge, a bit smaller than a city neighborhood:
fig, axes = plt.subplots(1, 3, figsize=(13, 4.8))
rows = []
for ax, res in zip(axes, [7, 8, 9]):
cell_ids = [h3.latlng_to_cell(la, lo, res) for la, lo in zip(pickups["lat"], pickups["lon"])]
grid = hex_grid(pd.Series(cell_ids).value_counts().rename("pickups").to_frame()).to_crs(epsg=3857)
grid.plot(column="pickups", cmap="magma_r", alpha=0.8, edgecolor="white", linewidth=0.3, ax=ax)
ctx.add_basemap(ax, source=ctx.providers.USGS.USTopo, zoom=11, attribution=False)
ax.set_title(f"resolution {res}: {len(grid)} cells")
ax.set_axis_off()
rows.append((res, h3.average_hexagon_edge_length(res, unit="km"),
h3.average_hexagon_area(res, unit="km^2"), len(grid)))
fig.tight_layout()
plt.show()
print(pd.DataFrame(rows, columns=["resolution", "edge_km", "area_km2", "occupied_cells"]).round(3).to_string(index=False))

resolution edge_km area_km2 occupied_cells
7 1.406 5.161 73
8 0.531 0.737 381
9 0.201 0.105 1111
Choose the resolution to match your question. Too coarse and the hotspots blur together. Too fine and most cells hold one or two points, so the colors show noise and not demand. A good starting point is a resolution where the busiest cells have dozens of points and the typical occupied cell has several. Here resolution 9 has 1,111 occupied cells, most of them holding a pickup or two, while resolution 7 has only 73, so each busy neighborhood is just one or two big hexagons.
How do I show a value per hexagon, such as the median fare?
groupby("cell").agg(...) computes any statistic per hexagon. Hexagons with only a few points give unreliable medians, so drop them first (here, fewer than 15 pickups):
by_cell = pickups.groupby("cell").agg(pickups=("fare", "size"), median_fare=("fare", "median"))
kept = by_cell[by_cell["pickups"] >= 15]
fares = hex_grid(kept).to_crs(epsg=3857)
ax = fares.plot(column="median_fare", cmap="viridis", alpha=0.85, edgecolor="white", linewidth=0.5,
legend=True, legend_kwds={"label": "Median fare ($)", "shrink": 0.6}, figsize=(8, 8))
ctx.add_basemap(ax, source=ctx.providers.USGS.USTopo)
ax.set_axis_off()
plt.show()
print(f"{len(kept)} of {len(by_cell)} cells have at least 15 pickups")
print(kept["median_fare"].describe()[["min", "50%", "max"]].round(2).to_dict())

47 of 381 cells have at least 15 pickups
{'min': 9.84, '50%': 15.78, 'max': 22.59}
In this data the fare was built to rise with distance from the Loop, so the center is dark (cheap) and the outer hexagons are green and yellow. Only 47 of the 381 hexagons pass the filter, and they are the ones around the busy neighborhoods. The >= 15 filter is the important part. Without it the map would show every one-pickup hexagon at its single fare, and the outer cells would look as trustworthy as the central ones.
How do I fill empty hexagons and smooth a heat map?
A groupby only produces cells that have at least one point. To cover a whole area, including the cells with zero pickups, ask H3 for every cell inside a polygon with h3.geo_to_cells(), then reindex the counts onto that list. h3.grid_disk(cell, 1) returns a cell and its six neighbors, which makes a smoothed count (the average of each cell and its neighbors) one line:
from shapely.geometry import box
study_area = box(-87.74, 41.78, -87.58, 41.98)
all_cells = sorted(h3.geo_to_cells(study_area, 8))
full = counts["pickups"].reindex(all_cells, fill_value=0)
smoothed = pd.Series({cell: np.mean([full.get(n, 0) for n in h3.grid_disk(cell, 1)]) for cell in full.index},
name="smoothed")
grid = hex_grid(smoothed.to_frame()).to_crs(epsg=3857)
fig, axes = plt.subplots(1, 2, figsize=(10, 6.4))
raw_grid = hex_grid(full.to_frame()).to_crs(epsg=3857)
for ax, frame, col, title in [(axes[0], raw_grid, "pickups", "Raw counts (empty cells included)"),
(axes[1], grid, "smoothed", "Smoothed with grid_disk(cell, 1)")]:
frame.plot(column=col, cmap="magma_r", alpha=0.8, edgecolor="white", linewidth=0.3, ax=ax)
ctx.add_basemap(ax, source=ctx.providers.USGS.USTopo, zoom=12, attribution=False)
ax.set_title(title)
ax.set_axis_off()
fig.tight_layout()
plt.show()
print(f"{len(all_cells)} cells in the study area, {(full == 0).mean():.0%} with no pickups")
print("busiest cell:", full.idxmax(), full.max(), "->", round(smoothed[full.idxmax()], 1), "after smoothing")

397 cells in the study area, 10% with no pickups
busiest cell: 882664c1a9fffff 581 -> 289.4 after smoothing
Smoothing spreads each cell's count over its neighbors, so one busy hexagon next to empty ones fades instead of standing alone. It turns a spiky map into a broader heat map, at the cost of the exact peak value: the busiest hexagon drops from 581 pickups to 289.4 after smoothing. h3.grid_disk(cell, 2) widens the neighborhood to 19 cells. Filling the empty cells also matters for comparisons: only 10% of the cells here are empty because the background pickups are scattered everywhere, but in real data a cell missing from the table is a cell with no activity, and the map should show it that way.
H3 hexagons vs a square grid vs hexbin
| H3 hexagons | Square grid (GeoPandas) | ax.hexbin() |
|
|---|---|---|---|
| Needs a spatial join | No, one function per point | Yes | No |
| Cells are comparable across datasets | Yes (same global ids) | Only if you share the grid | No (depends on the data extent) |
| Distance to each neighbor | Equal for all six | Differs between sides and corners | Equal |
| Roll up to a coarser level | h3.cell_to_parent(cell, res) |
Rebuild the grid | Rerun |
| Works on a basemap | Yes, after to_crs(3857) |
Yes | Awkward (needs plotting in Web Mercator) |
| Best for | Maps you join, compare or roll up | Simple fixed grids | A quick density look at points on a plain axes |
Use hexbin for a quick look. Use H3 when the cell ids will be joined to other tables (weather by cell, demand by cell and hour) or when you need several resolutions of the same data, since cell_to_parent() aggregates a fine grid into a coarser one.
Practical Tips
- Pick the resolution first. Print
h3.average_hexagon_edge_length(res, unit="km")for a few resolutions, and pick the one close to the scale of the question. - Mind the order. H3 returns
(lat, lng). Shapely, GeoPandas and GeoJSON use(lng, lat). Swap when you build polygons. - Filter thin cells before coloring a statistic. A median of two points is not a result. Set a minimum count.
- Fill zero cells when you compare areas. Reindex onto
h3.geo_to_cells(polygon, res)so empty places are shown as empty and not left off the map. - Convert before the basemap. Hexagons are in latitude and longitude. Call
.to_crs(epsg=3857)beforeadd_basemap(), or passcrs=. - Hexagons are not equal area at every latitude on the map. Web Mercator stretches shapes away from the equator. Compare cells by count or by statistics on the cell, not by how big they look.
- Version 3 code won't run.
geo_to_h3,h3_to_geo_boundaryandk_ringbecamelatlng_to_cell,cell_to_boundaryandgrid_diskin h3 4.