Skip to main content

Coordinate Reference Systems and Projections

How do we represent a round planet on a flat screen?

Author

Emanuel Goulart

Published

December 4, 2026

Prefer to run everything in a notebook instead of following along on the site? Open In Colab opens AUX_week1.ipynb, with all of Week 1’s content (text and code) in a single notebook (in Portuguese).

What is our reference system? Does every point need context?

A coordinate like (-27, -48) means nothing on its own. We need to know whether we are talking about degrees or meters, and which coordinate system the point refers to. And we can dig even deeper: which ellipsoid are we using?

Motivation

  • How do we locate objects on Earth?
  • Where do we place the origin of an axis?
  • What defines north and south?

Just as “10” means nothing without a unit (10 meters? 10 reais? 10 degrees?), a coordinate means nothing without a Coordinate Reference System (CRS). This context defines the origin, the unit and the model of the Earth used in our representation.

The Earth is not a perfect sphere

A recent image of planet Earth captured by the latest Artemis mission, Artemis II. Source: Artemis II. NASA. 04-02-2026.

A coordinate system (CRS) defines how the graphical representations in GIS tools are located and positioned on planet Earth. So if we start from the assumption that the Earth is a perfect sphere, we could describe a point as the tip of a vector touching the surface of a sphere.

Code
import numpy as np
import plotly.graph_objects as go

R = 1.0

theta = np.pi / 4
phi = np.pi / 3

x0 = R * np.sin(theta) * np.cos(phi)
y0 = R * np.sin(theta) * np.sin(phi)
z0 = R * np.cos(theta)

u = np.linspace(0, 2*np.pi, 80)
v = np.linspace(0, np.pi, 80)

x = R * np.outer(np.cos(u), np.sin(v))
y = R * np.outer(np.sin(u), np.sin(v))
z = R * np.outer(np.ones_like(u), np.cos(v))

sphere = go.Surface(
    x=x, y=y, z=z,
    opacity=0.4,
    colorscale="Blues",
    showscale=False
)

vector = go.Scatter3d(
    x=[0, x0],
    y=[0, y0],
    z=[0, z0],
    mode="lines+markers",
    line=dict(color="red", width=6),
    marker=dict(size=4),
    name="vector r"
)

point = go.Scatter3d(
    x=[x0],
    y=[y0],
    z=[z0],
    mode="markers",
    marker=dict(size=6, color="red"),
)

L = 1.5 * R

axes = [
    go.Scatter3d(x=[-L, L], y=[0, 0], z=[0, 0],
                 mode="lines", line=dict(color="black", width=4)),
    go.Scatter3d(x=[0, 0], y=[-L, L], z=[0, 0],
                 mode="lines", line=dict(color="black", width=4)),
    go.Scatter3d(x=[0, 0], y=[0, 0], z=[-L, L],
                 mode="lines", line=dict(color="black", width=4)),
]

layout = go.Layout(
    scene=dict(
        xaxis=dict(title="X", showbackground=True),
        yaxis=dict(title="Y", showbackground=True),
        zaxis=dict(title="Z", showbackground=True),
        aspectmode="cube"
    ),
    margin=dict(l=0, r=0, b=0, t=0)
)

fig = go.Figure(data=[sphere, vector, point] + axes, layout=layout)
fig.show()

Well… that assumes the Earth is round. However, the data show that the Earth’s shape is not exactly spherical: it is described as an ellipsoid of revolution, or a geoid. And no ellipsoid fits equally well everywhere on the globe, so an ellipsoid fitted for South America may differ from one fitted for Central Asia. Each of these fits gives rise to a datum. A datum is a mathematical model that anchors the coordinate system to the Earth. That is exactly why there are so many “WGS84s” out there: each datum is a different attempt to answer “where exactly does this imaginary sphere touch the real planet?”

The Earth’s gravity field (geoid). Source: ESA

Animation of the geoid — ESA

So a reference system defines the conventions that let us locate a point anywhere on Earth.

NoteConversion vs. transformation
  • Conversion: changing the projection while keeping the same datum. Pure math, lossless, 100% reversible.
  • Transformation: changing the datum. It involves empirically fitted models and can introduce a few meters of uncertainty.

Geographic vs. Projected CRS

Geographic CRS Projected CRS
Unit degrees (°) meters (usually)
Example WGS84 (EPSG:4326), SIRGAS2000 (EPSG:4674) SIRGAS2000 / UTM 22S (EPSG:31982)
Good for global data, web mapping, GPS measuring distance/area, local analysis
Problem 1° of longitude ≠ 1° of latitude in real distance only accurate near its center/zone

One degree of latitude is always ~111 km anywhere on the planet. One degree of longitude is not: it is ~111 km at the equator and shrinks to zero at the poles. That is why computing distance/area directly in degrees gives the wrong result (we show this in practice further down).

There is no projection without distortion. Every projection sacrifices some property, be it area, angle (shape), distance, etc. The question for us is which projection suits the analysis we want to run, keeping in mind that there is no “correct” projection.

Planet Earth in three different projections

Same data, very different shapes: the projection is an analytical decision, not just an aesthetic one, perhaps even a political one.

Code
world = gpd.read_file(
    "https://naturalearth.s3.amazonaws.com/110m_cultural/ne_110m_admin_0_countries.zip"
)

projections = [
    (ccrs.PlateCarree(),   'PlateCarree — Geographic',    '#457b9d'),
    (ccrs.Mercator(),      'Mercator — Conformal',        '#f4a261'),
    (ccrs.Mollweide(),     'Mollweide — Equal-Area',      '#e63946'),
]

fig, axes = plt.subplots(
    1, 3, figsize=(15, 6),
    subplot_kw={'projection': None}
)

for i, (proj, title, color) in enumerate(projections):
    ax = fig.add_subplot(1, 3, i + 1, projection=proj)
    ax.set_global()
    ax.add_feature(cfeature.OCEAN, facecolor='#e8f4f8')
    ax.add_feature(cfeature.LAND,  facecolor='#f0f0f0')
    for geom in world.geometry:
        ax.add_geometries(
            [geom], ccrs.PlateCarree(),
            facecolor=color, edgecolor='white', linewidth=0.5
        )
    ax.set_title(title, fontsize=11, fontweight='bold', pad=10)

plt.tight_layout()
plt.show()
Figure 1: The world in three projections: PlateCarree (geographic), Mercator and Mollweide (equal-area).

New world map released by the Government of Brazil, 2026. Source: IBGE

Fun Fact

The UN flag uses an equidistant projection.

Code
from matplotlib.patches import PathPatch
import matplotlib.path
import matplotlib.pyplot as plt
import matplotlib.ticker
from matplotlib.transforms import Bbox, BboxTransform
import numpy as np

import cartopy.crs as ccrs
import cartopy.feature as cfeature


# When drawing the flag, we can either use white filled land, or be a little
# more fancy and use the Natural Earth shaded relief imagery.
filled_land = True


blue = '#4b92db'

# We're drawing a flag with a 3:5 aspect ratio.
fig = plt.figure(figsize=[7.5, 4.5], facecolor=blue)
# Put a blue background on the figure.
blue_background = PathPatch(matplotlib.path.Path.unit_rectangle(),
                            transform=fig.transFigure, color=blue,
                            zorder=-1)
fig.patches.append(blue_background)

# Set up the Azimuthal Equidistant and Plate Carree projections
# for later use.
az_eq = ccrs.AzimuthalEquidistant(central_latitude=90)
pc = ccrs.PlateCarree()

# Pick a suitable location for the map (which is in an Azimuthal
# Equidistant projection).
ax = fig.add_axes([0.25, 0.24, 0.5, 0.54], projection=az_eq)

# The background patch is not needed in this example.
ax.patch.set_facecolor('none')
# The Axes frame produces the outer meridian line.
for spine in ax.spines.values():
    spine.update({'edgecolor': 'white', 'linewidth': 2})

# We want the map to go down to -60 degrees latitude.
ax.set_extent([-180, 180, -60, 90], ccrs.PlateCarree())

# Importantly, we want the axes to be circular at the -60 latitude
# rather than cartopy's default behaviour of zooming in and becoming
# square.
_, patch_radius = az_eq.transform_point(0, -60, pc)
circular_path = matplotlib.path.Path.circle(0, patch_radius)
ax.set_boundary(circular_path)

if filled_land:
    ax.add_feature(
        cfeature.LAND, facecolor='white', edgecolor='none')
else:
    ax.stock_img()

gl = ax.gridlines(crs=pc, linewidth=2, color='white', linestyle='-')
# Meridians every 45 degrees, and 4 parallels.
gl.xlocator = matplotlib.ticker.FixedLocator(np.arange(-180, 181, 45))
parallels = np.arange(-30, 70, 30)
gl.ylocator = matplotlib.ticker.FixedLocator(parallels)


plt.show()

Projections - the UTM System - Universal Transverse Mercator

The Universal Transverse Mercator (UTM) coordinate system has its origin at the equator, at a specific longitude. To reduce distortion, the world is divided into 60 zones, each 6 degrees of longitude wide. The zones are numbered from 1 to 60, in order from west to east.

Code
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

# Create a list of integers from 1 - 60
zones = range(1, 61)

# Create a figure
fig = plt.figure(figsize=(18, 6))

# Loop through each zone in the list
for zone in zones:

    # Add GeoAxes object with specific UTM zone projection to the figure
    ax = fig.add_subplot(1,
                        len(zones),
                        zone,
                        projection=ccrs.UTM(zone=zone,
                                            southern_hemisphere=True)
                                            )

    # Add coastlines, gridlines and zone number for the subplot
    ax.coastlines(resolution='110m')
    ax.gridlines()
    ax.set_title(zone)

# Add a supertitle for the figure
fig.suptitle("UTM Projection - Zones")

# Display the figure
plt.show()

NoteNothing new under the sun

Young grasshopper, there will always be a website or project that someone already built to make your life easier.

How can we reproject geospatial data?

One of the most classic and traditional ways to handle geospatial data is the robust and stable GDAL project (GDAL-WEBSITE). GDAL is the engine running under the hood of many software packages around the world, such as our beloved QGIS. Anything you can imagine doing with geospatial data, vector or raster, someone has most likely already done with GDAL. Extremely complete and powerful, the library has an open-source license and an engaged community, which organizes one of the largest geospatial events in the world: FOSS4G.

To illustrate these concepts of data transformation and reprojection, we will use an engine that works under the hood of GDAL to transform data, called PROJ. We will work with its Python bindings.

pyproj under the hood

pyproj is the Python library that talks to PROJ, the coordinate transformation engine used by practically the whole geospatial ecosystem (QGIS, GDAL, GeoPandas, Cartopy, and the list goes on). The Transformer class converts a point from one CRS to another:

Code
transformer = pyproj.Transformer.from_crs(
    "EPSG:4326",   # WGS84, geographic
    "EPSG:31982",  # SIRGAS2000 / UTM zone 22S
    always_xy=True,
)

lon, lat = -48.5495, -27.5973  # Florianópolis
x, y = transformer.transform(lon, lat)
print(f"Geographic:  {lon:.4f}°, {lat:.4f}°")
print(f"Projected:   x={x:,.1f} m, y={y:,.1f} m")
Geographic:  -48.5495°, -27.5973°
Projected:   x=741,871.5 m, y=6,945,008.4 m

Notice: we started in degrees and ended up in meters from an arbitrary origin of the UTM zone. That is what a projection does, point by point.

Visualizing distortion

A direct way to see what a projection does is to take a regular grid of meridians (longitude) and parallels (latitude), in degrees, and look at it after it has been projected.

Code
lons = np.arange(-75, -30, 5)
lats = np.arange(-35, 10, 5)

to_utm = pyproj.Transformer.from_crs("EPSG:4326",
                                    "EPSG:31982",
                                    always_xy=True
                                    )

fig, axes = plt.subplots(1, 2, figsize=(13, 6))

# original grid, in degrees
ax = axes[0]
for lon in lons:
    ax.plot([lon] * len(lats), lats, color="#457b9d", linewidth=0.8)
for lat in lats:
    ax.plot(lons, [lat] * len(lons), color="#457b9d", linewidth=0.8)
ax.set_title("Geographic grid (degrees)")
ax.set_xlabel("longitude")
ax.set_ylabel("latitude")
ax.set_aspect("equal")

# the same grid, projected to a single UTM zone (22S)
ax = axes[1]
for lon in lons:
    lat_line = np.linspace(-35, 10, 60)
    x, y = to_utm.transform([lon] * len(lat_line), lat_line)
    ax.plot(x, y, color="#e63946", linewidth=0.8)
for lat in lats:
    lon_line = np.linspace(-75, -30, 60)
    x, y = to_utm.transform(lon_line, [lat] * len(lon_line))
    ax.plot(x, y, color="#e63946", linewidth=0.8)
ax.set_title("Same grid, projected (UTM 22S)")
ax.set_xlabel("x (m)")
ax.set_ylabel("y (m)")
ax.set_aspect("equal")

plt.tight_layout()
plt.show()
Figure 2: A regular 5° grid in degrees (left) and the same grid projected to a single UTM zone (right). Far from the zone’s central meridian the distortion blows up, which is exactly why UTM is split into narrow zones.

The projected grid warps as it moves away from the central meridian of zone 22S. This is not a bug; it is a consequence of the projection. It also explains why UTM is divided into 60 narrow zones of 6° each: each zone is only accurate near its own center.

Visualizing with Cartopy

Same data, three projections, three different decisions about South America:

Code
projections = [
    (ccrs.PlateCarree(), "PlateCarree — geographic"),
    (ccrs.Mercator(), "Mercator — conformal"),
    (ccrs.AlbersEqualArea(central_longitude=-50,
                            central_latitude=-20), "Albers — equal-area"),
]

fig = plt.figure(figsize=(15, 5))
for i, (proj, title) in enumerate(projections, start=1):
    ax = fig.add_subplot(1, 3, i, projection=proj)
    ax.set_extent([-85, -30, -50, 20],
                    crs=ccrs.PlateCarree()
                    )
    ax.add_feature(cfeature.LAND, facecolor="#f0f0f0")
    ax.add_feature(cfeature.OCEAN, facecolor="#e8f4f8")
    ax.add_feature(cfeature.BORDERS, linewidth=0.5)
    ax.coastlines(linewidth=0.6)
    ax.set_title(title, fontsize=11, fontweight="bold")

plt.tight_layout()
plt.show()
Figure 3: PlateCarree (geographic, no correction at all), Mercator (conformal: preserves angles but distorts area away from the equator) and Albers Equal Area centered on Brazil (preserves area).

Going further with maps in Python

Gridlines and labels

Cartopy will be our workhorse for static maps. It has features for everything. Here we explore how to draw meridians and parallels with labels directly on the axes.

Code
fig = plt.figure(figsize=(7, 7))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
ax.set_extent([-75, -33, -34, 6], crs=ccrs.PlateCarree())
ax.add_feature(cfeature.LAND, facecolor="#f0f0f0")
ax.add_feature(cfeature.OCEAN, facecolor="#e8f4f8")
ax.coastlines(linewidth=0.6)

gl = ax.gridlines(draw_labels=True, linewidth=0.5, color="gray", alpha=0.6)
gl.top_labels = False
gl.right_labels = False

ax.set_title("Brazil with labeled gridlines", fontsize=12, fontweight="bold")
plt.show()
Figure 4: Gridlines with automatic latitude/longitude labels over Brazil.

TIP: Where can you get country boundary data? The go-to reference is always Natural Earth Data.

GeoPandas integrates with it directly through Geodatasets. In R, the library is better structured: R Natural Earth

Reprojection: vector vs. raster

The two kinds of geospatial data are not reprojected the same way. When we have a data matrix (raster), we need to reproject and resample the values of that matrix into a new coordinate system.

Let’s take a closer look:

  • Vector: each vertex is a point, and a point becomes another point directly through the transformation formula.
  • Raster: reprojecting means creating a new grid, with pixels in different positions, and then resampling (interpolating) the original values onto that new grid. It is more computationally expensive and usually loses a bit of information. So here’s a tip: when you are working with both vector and raster data, whenever possible reproject the vectors to the raster’s CRS, not the other way around.

Vector: there is no such thing as area in degrees

One of the most common mistakes when you start working with geospatial data is computing area in a geographic system, in degrees, instead of in a projection.

Code
sc = geobr.read_state(code_state="SC", year=2020)

area_graus = sc.geometry.area.iloc[0]          # in degrees² -- means absolutely nothing

# first reproject to a UTM projection for the zone of the area of interest
area_km2 = sc.to_crs(31982).geometry.area.iloc[0] / 1e6  # reprojected to meters, then km²

print(f"Area 'computed' directly in degrees:  {area_graus:.4f} (no real unit, useless)")
print(f"Area after reprojecting (UTM):        {area_km2:,.0f} km²")
Area 'computed' directly in degrees:  8.7244 (no real unit, useless)
Area after reprojecting (UTM):        95,707 km²

The first number is not “slightly inaccurate”: it basically represents no area at all, because degree² is not a unit of area on the Earth’s surface. Only after reprojecting to a CRS in meters does the calculation make sense.

Raster: the order of operations

When drawing a reprojected raster with Cartopy, ax.set_extent() must come before imshow(), otherwise the resampling uses the wrong extent. Often your plotting is correct but the visible extent of your map isn’t set up.

Code
img = np.linspace(0, 1, 10_000).reshape(100, 100)

img_extent = (-49.5, -48.0, -28.2, -27.0)  # bbox near Florianópolis/SC
img_proj = ccrs.PlateCarree()

map_proj = ccrs.RotatedPole(pole_longitude=120.0,                           pole_latitude=70.0
)
map_extent = (-50.0, -47.5, -28.6, -26.6)

fig, axs = plt.subplots(
    1, 2, figsize=(11, 5), subplot_kw={"projection": map_proj},
    sharex=True, sharey=True, layout="constrained",
)

axs[0].set_title("✗ imshow BEFORE set_extent")
axs[0].imshow(img, extent=img_extent,
                    origin="lower", transform=img_proj,
                    cmap="viridis"
                    )
axs[0].set_extent(map_extent,
                crs=img_proj
                )

axs[1].set_title("✓ imshow AFTER set_extent")
axs[1].set_extent(map_extent,
                    crs=img_proj
                    )
axs[1].imshow(img, extent=img_extent, origin="lower", transform=img_proj, cmap="viridis")

for ax in axs:
    ax.coastlines(linewidth=0.6)
    ax.gridlines(draw_labels=False, linewidth=0.3)

plt.show()
Figure 5: Same synthetic raster, same target projection (RotatedPole): the only difference between the two panels is the ORDER in which set_extent() is called.

SIRGAS - the Brazilian Standard

SIRGAS2000 (Geocentric Reference System for the Americas) has been Brazil’s official datum since 2005 (IBGE), replacing the old SAD69 and Córrego Alegre. It is geocentric and, in practice, compatible with GPS/WGS84 (the differences are centimeters, not meters), and it is the default for every official IBGE dataset, including the geobr data we used in the previous notebooks (EPSG:4674).

Since Brazil is too wide for a single UTM zone, the territory is covered by several SIRGAS2000/UTM zones, one every 6° of longitude. Just as there is WGS84/UTM, there is also SIRGAS2000/UTM, as projected forms of the reference system.

Below, we color each state by the UTM zone of its centroid.

Code
states = geobr.read_state(year=2020)
states["utm_zone"] = states.geometry.centroid.x.apply(lambda lon: int((lon + 180) // 6) + 1)

fig, ax = plt.subplots(figsize=(7, 8))
states.plot(
    ax=ax,
    column="utm_zone",
    categorical=True,
    cmap="tab10",
    edgecolor="white",
    linewidth=0.6,
    legend=True,
    legend_kwds={"title": "UTM zone", "loc": "lower left"},
)

minx, miny, maxx, maxy = states.total_bounds
zone_min, zone_max = int(states["utm_zone"].min()), int(states["utm_zone"].max())
for zone in range(zone_min, zone_max + 2):
    lon = -180 + 6 * (zone - 1)  # western boundary of the zone
    if minx - 1 <= lon <= maxx + 1:
        ax.axvline(lon, color="black", linewidth=0.7, linestyle="--", alpha=0.5)
        if lon < maxx:
            ax.text(lon + 0.3, maxy + 0.3, f"{zone}", fontsize=8, ha="left", va="bottom")

ax.set_xlim(minx - 1, maxx + 1)
ax.set_ylim(miny - 1, maxy + 1.5)
ax.set_title("UTM zones by state", fontsize=12, fontweight="bold")
ax.set_axis_off()
plt.show()
Figure 6: Brazilian states colored by the UTM zone of their centroid, with dashed lines marking the zone boundaries (meridians every 6°). Notice how wide states (such as Amazonas) span more than one zone; in practice, you pick the zone closest to the center of your area of interest.

Other Modern Grids

Many other grids have emerged as solutions to practical problems. One of them is H3, the hexagon grid created by Uber, which spread as a standard grid for dynamic pricing analysis and is gaining a lot of traction in the geospatial community.

Starting at minute 9:30 of https://www.youtube.com/watch?v=ay2uwtRO3QE&t=573s, this Uber software engineer explains how they arrived at hexagons as the standard shape for Uber’s grids.

Hexagons - H3

Instead of square grids with 4 neighbors, hexagons offer a solution to this problem. Just as the hypotenuse is always longer than the legs of a right triangle, in a square grid the diagonal neighbors are farther away; in a hexagon, the distances to every side are uniform. Each hexagon has 6 neighbors, all at the same distance from the center. That is why it became the industry standard for things like dynamic pricing, ride density and any spatial analysis at scale.

“Squares (like geohash or quadtree grids) have uneven neighbor distances and distort heavily as you move across the map, especially near poles”

Code
from matplotlib.patches import Rectangle, RegularPolygon

fig, axes = plt.subplots(1, 2, figsize=(12, 6))

# --- Square grid ---
ax = axes[0]
s = 1.0
for i in range(-2, 3):
    for j in range(-2, 3):
        color = "#f0f0f0" if (i, j) != (0, 0) else "#e63946"
        ax.add_patch(Rectangle((i - s/2, j - s/2), s, s,
                                facecolor=color, edgecolor="white", linewidth=1.5))

orth = [(1, 0), (-1, 0), (0, 1), (0, -1)]
diag = [(1, 1), (1, -1), (-1, 1), (-1, -1)]

for dx, dy in orth:
    ax.plot([0, dx], [0, dy], color="#457b9d", linewidth=2.5, zorder=3)
for dx, dy in diag:
    ax.plot([0, dx], [0, dy], color="#f4a261", linewidth=2.5, zorder=3)

ax.plot(0, 0, "o", color="white", markersize=6, zorder=4)
ax.annotate("1.0", xy=(0.55, 0.08), color="#457b9d", fontsize=11, fontweight="bold")
ax.annotate("√2 ≈ 1.41", xy=(0.55, 0.62), color="#f4a261", fontsize=11, fontweight="bold")

ax.set_xlim(-2.2, 2.2)
ax.set_ylim(-2.2, 2.2)
ax.set_aspect("equal")
ax.set_axis_off()
ax.set_title("Square grid — 2 different distances", fontsize=11, fontweight="bold")

# --- Hexagonal grid ---
ax = axes[1]
R = 1.0
offsets_axial = [(1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1), (0, 0)]

def axial_to_xy(q, r, size):
    x = size * np.sqrt(3) * (q + r / 2)
    y = size * 1.5 * r
    return x, y

centers = {(q, r): axial_to_xy(q, r, R) for q, r in offsets_axial}

for (q, r), (x, y) in centers.items():
    color = "#f0f0f0" if (q, r) != (0, 0) else "#e63946"
    hexagon = RegularPolygon((x, y), numVertices=6, radius=R,
                              orientation=0, facecolor=color,
                              edgecolor="white", linewidth=1.5)
    ax.add_patch(hexagon)

cx, cy = centers[(0, 0)]
for (q, r), (x, y) in centers.items():
    if (q, r) != (0, 0):
        ax.plot([cx, x], [cy, y], color="#457b9d", linewidth=2.5, zorder=3)

ax.plot(cx, cy, "o", color="white", markersize=6, zorder=4)
dist = np.sqrt(3) * R
ax.annotate(f"{dist:.2f} (always)", xy=(cx + 0.25, cy - 1.65), color="#457b9d",
            fontsize=11, fontweight="bold")

ax.set_xlim(-3.2, 3.2)
ax.set_ylim(-3.2, 3.2)
ax.set_aspect("equal")
ax.set_axis_off()
ax.set_title("Hexagonal grid — 1 single distance", fontsize=11, fontweight="bold")

plt.tight_layout()
plt.show()

Hexagons minimize these distortions, preserve area more uniformly, avoid diagonal inconsistencies, and produce cleaner, more natural-looking spatial clusters.

This uniformity of distance is what makes H3 so widely used for neighborhood analysis, routing and spatial aggregation. Uber doesn’t need to “correct” the distance depending on which neighbor is being compared.

Code
muni = geobr.read_municipality(code_muni=4205407, year=2020)  # Florianópolis
geom = muni.geometry.iloc[0]

shape = h3.geo_to_h3shape(geom)
cells = h3.h3shape_to_cells(shape, 8)

hex_polygons = [
    Polygon([(lng, lat) for lat, lng in h3.cell_to_boundary(cell)])
    for cell in cells
]
hex_gdf = gpd.GeoDataFrame({"h3_cell": list(cells)}, geometry=hex_polygons, crs="EPSG:4326")

fig, ax = plt.subplots(figsize=(7, 7))
muni.plot(ax=ax, color="#f0f0f0", edgecolor="#898781", linewidth=1)
hex_gdf.plot(ax=ax, facecolor="none", edgecolor="#e63946", linewidth=0.5)
ax.set_title(f"Florianópolis in {len(hex_gdf)} H3 hexagons (res. 8)", fontsize=12, fontweight="bold")
ax.set_axis_off()
plt.show()
Figure 7: Florianópolis covered by H3 hexagons, resolution 8 (~0.7 km² per hexagon).

Each hexagon has a unique index (h3_cell, like 88a91bcd51fffff) that serves as a key for spatial aggregation, only on a uniform grid instead of IBGE’s boundaries.

Interactive H3

A static map shows the grid, but hides how useful H3 can be in practice, where each cell is an individual index at different levels. With folium (which wraps the JS library Leaflet) we can build an interactive map: hover over any hexagon to see its h3_cell and a metric computed cell by cell.

Let’s cover Catolé do Rocha, in the semi-arid interior (sertão) of Paraíba.

Code
import folium
import branca.colormap as cm

muni = geobr.read_municipality(code_muni=2504306, year=2020)  # Catolé do Rocha - PB
geom = muni.geometry.iloc[0]
centroid = geom.centroid

shape = h3.geo_to_h3shape(geom)
cells = h3.h3shape_to_cells(shape, 8)

hex_polygons = [
    Polygon([(lng, lat) for lat, lng in h3.cell_to_boundary(cell)])
    for cell in cells
]
hex_gdf = gpd.GeoDataFrame({"h3_cell": list(cells)}, geometry=hex_polygons, crs="EPSG:4326")

# distance from each hexagon center to the center of the municipality (~km, approximating 1° ≈ 111 km)
hex_gdf["dist_km"] = hex_gdf.geometry.centroid.apply(lambda p: centroid.distance(p) * 111).round(2)

colormap = cm.linear.YlOrRd_09.scale(hex_gdf["dist_km"].min(), hex_gdf["dist_km"].max())
colormap.caption = "Distance to the center of the municipality (km)"

m = folium.Map(location=[centroid.y, centroid.x], zoom_start=12, tiles="cartodbpositron")

folium.GeoJson(
    muni,
    style_function=lambda _: {"fillOpacity": 0, "color": "#333333", "weight": 2},
).add_to(m)

folium.GeoJson(
    hex_gdf,
    style_function=lambda feat: {
        "fillColor": colormap(feat["properties"]["dist_km"]),
        "color": "white",
        "weight": 0.6,
        "fillOpacity": 0.75,
    },
    highlight_function=lambda _: {"weight": 2, "color": "black"},
    tooltip=folium.GeoJsonTooltip(
        fields=["h3_cell", "dist_km"],
        aliases=["H3 cell:", "Distance to center (km):"],
        localize=True,
    ),
).add_to(m)

colormap.add_to(m)
m
Make this Notebook Trusted to load map: File -> Trust Notebook
Figure 8: Catolé do Rocha (PB) covered by H3 hexagons, resolution 8. Hover over any hexagon to see its index and its distance to the center of the municipality.

Notice that the metric (dist_km) was computed once per cell and lives alongside h3_cell in the GeoDataFrame. That is exactly how you aggregate any variable (population density, ride-hailing trips, emergency calls…) on an H3 grid: one row per cell, one index, one value.

Did you notice anything wrong with this calculation? Let’s try to fix it…

NoteExercise: build your own hexagon map

Pick one of the cities below (or another of your choice: look up the code_muni on the IBGE site or filter geobr.read_municipality() by name, as we did in Figure 6) and repeat the process above:

City State code_muni
Bonito MS 5002308
Paraty RJ 3303807
Lençóis BA 2919207
Bento Gonçalves RS 4302105
  1. Download the municipality polygon with geobr.read_municipality(code_muni=..., year=2020).
  2. Generate the cells with h3.geo_to_h3shape() and h3.h3shape_to_cells(). Try different resolutions (7, 8, 9) and see how the number of cells changes.
  3. Compute a metric per cell: it can be the distance to the center (as here), the area of each hexagon, or even a random value simulating “density”.
  4. Build the map with folium.GeoJson() and a GeoJsonTooltip showing h3_cell and the metric you chose.

Compare with a classmate who picked a different city: does the number of hexagons change a lot between a small and a large city? And is resolution 9 still feasible for a huge municipality, or does the map get too heavy?

References

Artwork by Joaquín Torres García - América Invertida (Inverted America)