04

Clusters

Reef clusters around the world (and where communities live near them!) Hand-coded

#30DayMapChallenge prompt: Clusters of something. Hotspots, groups, things that gather together.

Why this map

Warm-water coral reefs are the most biodiverse (and beautiful) marine ecosystems out there. Sadly, we're killing them. I wanted to show where in the world this super-biodiversity hotspots are, how they cluster around each other, and how coastal communities cluster around them. At first glance, I'm not sure I'm seeing that clustering!

It also serves as a map of places to consider dropping everything and moving to live in, so I can fullfil my dream to become an ocean warrior.

Data sources

Global distribution of warm-water coral reefs, version 4.1 ↗

From
UNEP-WCMC, WorldFish Centre, WRI and TNC, compiled mainly from the Millennium Coral Reef Mapping Project (IMaRS-USF and IRD) and the World Atlas of Coral Reefs (Spalding et al. 2001)
What
17,504 reef outlines (316,706 separate pieces, 151,390 km² in total) plus 925 reefs recorded only as points. Shallow, warm-water coral reefs only: no cold-water coral reefs and no rocky reefs. On this map the outlines are cut along a grid of 1,729 hexagons (H3 resolution 3) and each hexagon shows the share of its area that is reef. The 925 point-only reefs have no area, so they aren't in the totals.
Time
Version 4.1, released March 2021. The outlines come from surveys and satellite images dated 1968–2018, most of them from 1999–2002 (the Millennium Coral Reef Mapping Project's Landsat images). Downloaded 4 Nov 2026.
Resolution
Varies by source. 64% of the reef area comes from the Millennium Coral Reef Mapping Project (30 m Landsat pixels, about 1:50,000), and about half of that from its maps marked 'unvalidated'; 16% from the Great Barrier Reef Marine Park Authority's coastal features (1:250,000); about 5% from 1990 navigation charts (1:1,000,000). Only 18 outlines are marked expert-verified. On the map everything is summed into hexagons of 7,700–14,900 km², so single reefs can't be seen.
Licence
UNEP-WCMC General Data License (excluding WDPA): non-commercial use only; may be published if the data can't be downloaded and the citation, year of release and a link to www.unep-wcmc.org are visible. Requested citation: UNEP-WCMC, WorldFish Centre, WRI, TNC (2010). Global distribution of warm-water coral reefs, compiled from multiple sources including the Millennium Coral Reef Mapping Project. Version 4.0. Includes contributions from IMaRS-USF and IRD (2005), IMaRS-USF (2005) and Spalding et al. (2001). Cambridge (UK): UNEP World Conservation Monitoring Centre. URL: http://data.unep-wcmc.org/datasets/1 (the citation still says Version 4.0; the file is v4.1, released March 2021).

GHS-POP R2023A population grid, 2020 ↗

From
European Commission, Joint Research Centre (JRC), Global Human Settlement Layer (Schiavina, Freire, Carioli and MacManus 2023), built from CIESIN's GPWv4.11 census data
What
Estimated number of residents in every grid cell worldwide for 2020, one global GeoTIFF. Counts where people live, not where they work or visit, so tourists at reef resorts aren't in it. Used here for the number of people living within 30 km of a reef.
Time
Estimates for 2020, projected forward from national censuses taken 2001–2015 (129 of 249 countries and territories counted in 2010 or 2011). Release R2023A, file dated 24 Sep 2024. Downloaded 4 Nov 2026.
Resolution
30 arc-second cells (about 1 km at the equator). Each country's census totals are spread over its census areas according to where satellite images show buildings, so a single cell is a model estimate, not a headcount. Totals over larger areas, such as a 30 km zone around a reef, are more reliable. How small the census areas are varies by country.
Licence
CC BY 4.0 ('The GHSL data are provided under the Creative Commons Attribution 4.0 International (CC BY 4.0) license'). Cite: Schiavina, M., Freire, S., Carioli, A., MacManus, K. (2023). GHS-POP R2023A – GHS population grid multitemporal (1975-2030). European Commission, Joint Research Centre (JRC). doi:10.2905/2FF68A52-5B5B-4A22-8F40-C41DA8332CFE. Method: Pesaresi, M. et al. (2024). Advances on the Global Human Settlement Layer by joint assessment of Earth Observation and population survey data. International Journal of Digital Earth 17(1). doi:10.1080/17538947.2024.2390454.

How it was made

Pythonfoliumgeopandash3shapelynumpypandasrasterio
See the code (map.py)
"""
Day 4 · Clusters
The prompt: Clusters of something. Hotspots, groups, things that gather together.

What I'm mapping: Reefs around the world
"""

from pathlib import Path

import folium
import geopandas as gpd

from mapkit import palette as P
from mapkit.folium_style import add_basemap, style_map, add_legend, add_title, add_credit

import h3
from shapely.geometry import Polygon

import math
import numpy as np
import pandas as pd
import rasterio
import shapely
from rasterio import features
from rasterio.transform import from_origin
from rasterio.warp import reproject, Resampling
from shapely.geometry import box

HERE = Path(__file__).parent      # this day's folder
DATA = HERE / "data"              # put the data files you download in here

# Set up a map
m = folium.Map(location=[0, 180], zoom_start=2, tiles=None)
add_basemap(m, "dark")           # background map: also "light-nolabels", "dark", "osm", "mapbox"
style_map(m)                      # the site's font + ink-outlined buttons

# Understanding the reef data
reefs_outlines = gpd.read_file(DATA / "14_001_WCMC008_CoralReefs2021_v4_1/01_Data/WCMC008_CoralReef2021_Py_v4_1.shp")
reefs_points = gpd.read_file(DATA / "14_001_WCMC008_CoralReefs2021_v4_1/01_Data/WCMC008_CoralReef2021_Pt_v4_1.shp")
#print(reefs_outlines.describe())  # gives a summary of the numeric columns, does not say much about the text columns.
#print(len(reefs_outlines)) #how many reefs there are.
print(reefs_outlines.columns)
#print(reefs_outlines.head()) #the first 5 rows of the data, to see what it looks like.
#print(reefs_outlines.crs)
#print(reefs_outlines.geometry.type.value_counts())
#print(reefs_outlines.bounds)
#print(reefs_points.bounds)

#Calculating reef dimensions
reefs_width=reefs_outlines.bounds.maxx.max() - reefs_outlines.bounds.minx.min()
reefs_height=reefs_outlines.bounds.maxy.max() - reefs_outlines.bounds.miny.min()
print(f"reefs width: {reefs_width}, reefs height: {reefs_height}")
print(f"Total area of reefs: {reefs_outlines['GIS_AREA_K'].sum()} km²")

# Breaking down into single pieces
# .reset_index(drop=True) renumbers the pieces 0, 1, 2… Without it, all pieces of one
# reef share its old row number, and the .loc[west, ...] step below can pick the wrong rows.
reefs_single_pieces=reefs_outlines.explode(index_parts=False).reset_index(drop=True)
print(f"Number of single reef pieces: {reefs_single_pieces.shape[0]}")


# (AI HELP) Move the western hemisphere 360° east
# Reefs either side of the 180° line (Fiji, Kiribati, Tuvalu…) are stored at
# +179° and −179°: neighbours in real life, but at opposite ends of the map in
# numbers. Counting longitude 0–360 instead of −180–180 puts them side by side.
# Safe here because no reef piece crosses 0° (the Greenwich meridian).
west = reefs_single_pieces.bounds["maxx"] < 0     # True/False per row: True = entirely west of 0°
reefs_single_pieces.loc[west, "geometry"] = (
    reefs_single_pieces.loc[west, "geometry"].translate(xoff=360)   # slide those rows 360° east
)

# Check: every longitude should now be between 0 and 360
bounds = reefs_single_pieces.bounds
print(f"Longitudes now run from {bounds['minx'].min():.1f}° to {bounds['maxx'].max():.1f}°")


# (AI HELP) Measure each piece in km²
# Degrees can't measure area (a degree of longitude shrinks towards the poles),
# so measure in an equal-area system: EPSG:6933, in metres. The converted copy
# is temporary; the table itself stays in degrees, which H3 and folium need.
reefs_single_pieces["km2"] = reefs_single_pieces.to_crs(6933).area / 1_000_000   # m² → km²

# Check: should match UNEP-WCMC's own total (GIS_AREA_K), 151,390 km²
print(f"Total reef area: {reefs_single_pieces['km2'].sum():,.0f} km²")

# Making hexagons to cluster the reefs in
all_hexagons = set()  # start empty; a set keeps each ID only once
RES = 3              # Hexagon resolution: 0 = huge, 15 = tiny. 3 is about 120 km across, 4 about 45 km.
for reef in reefs_single_pieces.itertuples():
    point = reef.geometry.representative_point()  # one point guaranteed to be inside the reef's polygon
    cell = h3.latlng_to_cell(point.y, point.x, RES) # the point's hexagon id
    hexagons_nearby = h3.grid_disk(cell, 1) # that hexagon and its 6 neighbours
    all_hexagons.update(hexagons_nearby) # add non-duplicates to the set

print(f"Hexagons near reefs: {len(all_hexagons):,}")

# Convert the hexagon ID to a polygon in lat/lon degrees
all_hexagons = list(all_hexagons)  # convert the set to a list, so IDs and shapes stay in the same order
list_of_hexagons = list()
for hex_id in all_hexagons:
    corners = h3.cell_to_boundary(hex_id) # gives the corners of the hexagon as a list of (lat, lon) pairs
    # (AI HELP for this line)  Swap to (lng, lat) for shapely, and apply the 0–360 fix from 3b
    fixed = [(lng + 360 if lng < 0 else lng, lat) for lat, lng in corners]
    hex_polygon = Polygon(fixed) # convert that list to a shapely polygon, which folium can draw
    list_of_hexagons.append(hex_polygon)

hexagons = gpd.GeoDataFrame({"cell": all_hexagons}, geometry=list_of_hexagons, crs=4326)

# Checks
print(f"Hexagons in table: {len(hexagons):,}")    # 4,162 at RES = 3 (12,035 at RES = 4)
widest = (hexagons.bounds["maxx"] - hexagons.bounds["minx"]).max()
print(f"Widest hexagon: {widest:.1f}°")           # about 2° at RES = 3; near 360 = something wrapped


# Cookie cutter, cut each reef into hexagos.
# Each bit keeps the "cell" ID of the hexagon it landed in.
reef_bits = gpd.overlay(
    reefs_single_pieces[["geometry"]],   # just the shapes; the other columns aren't needed
    hexagons,                            # brings the "cell" column along
    how="intersection",                  # keep only where reefs and hexagons overlap
    keep_geom_type=True,                 # drop slivers that are only a line/point on an edge
)
reef_bits["km2"] = reef_bits.to_crs(6933).area / 1_000_000   # measure each bit (equal-area, m² → km²)

# Add up all the bits in the same hexagon
reef_per_hexagon = reef_bits.groupby("cell")["km2"].sum()
print(f"Hexagons with reef: {len(reef_per_hexagon):,}")               # 1,729
print(f"Reef area after cutting: {reef_per_hexagon.sum():,.0f} km²")  # still 151,390: nothing lost or counted twice

# Attach the totals to the hexagon table; how="inner" drops the empty neighbour hexagons
hexagons = hexagons.merge(reef_per_hexagon.rename("reef_km2").reset_index(), on="cell", how="inner")

# Reef as a % of each hexagon (H3 hexagons vary in size; here 7,700–14,900 km²)
hexagons["hex_km2"] = [h3.cell_area(cell, unit="km^2") for cell in hexagons["cell"]]
hexagons["reef_pct"] = hexagons["reef_km2"] / hexagons["hex_km2"] * 100
print(hexagons.sort_values("reef_pct", ascending=False).head())   # the densest hexagons


#AI FROM HERE
#step 6 · Draw them. Your basemap is "dark". The berry ramp runs from pale pink to deep plum, so on dark the densest reefs would disappear into the background. The code flips the ramp so that the most reef is the brightest. If you'd rather use the "light" basemap, delete the [::-1].
# ── STEP 6 · Draw the hexagons, coloured by reef % ──────────────────────────
EDGES = [0.01, 0.1, 1, 10]                     # band edges in %: each band is 10× the one before
LABELS = ["under 0.01%", "0.01–0.1%", "0.1–1%", "1–10%", "over 10%"]
COLOURS = P.ramp("berry", 5)[::-1]             # flipped for a dark basemap: most reef = brightest

def band_colour(pct):
    """The colour of the band this % falls in."""
    for edge, colour in zip(EDGES, COLOURS):
        if pct <= edge:
            return colour
    return COLOURS[-1]                         # above the last edge: over 10%

hexagons["colour"] = hexagons["reef_pct"].apply(band_colour)
hexagons["label"] = [
    f"{pct:.2f}% of this hexagon is reef ({km2:,.1f} km²)"
    for pct, km2 in zip(hexagons["reef_pct"], hexagons["reef_km2"])
]

reef_layer = folium.FeatureGroup(name="Coral reefs")   # its own layer, so it gets an on/off box
folium.GeoJson(
    hexagons[["label", "colour", "geometry"]],          # only what the page needs: keeps map.html small
    style_function=lambda feature: {
        "fillColor": feature["properties"]["colour"],
        "color": feature["properties"]["colour"],       # outline in the same colour: no grid lines
        "weight": 0.5,
        "fillOpacity": 0.85,
    },
    tooltip=folium.GeoJsonTooltip(fields=["label"], labels=False),
).add_to(reef_layer)
reef_layer.add_to(m)

add_legend(m, "Share of each hexagon that is coral reef", dict(zip(LABELS, COLOURS)), shape="square")


#Step 7 · People within 30 km of a reef

#7a · Shrink the population grid (takes about 90 seconds the first time, then it's saved)
# ── 7a · Shrink the population grid, adding up people, and save it ──────────
# The full grid is ~7.4 GB in memory. We only need 40°N–40°S, and cells of 2.5'
# (about 4.6 km: 5 × 5 of the original 1 km cells) are plenty for a 30 km zone.
# Resampling.sum ADDS the people of the 25 small cells, so no one is lost.
POP_FILE = DATA / "GHS_POP_E2020_GLOBE_R2023A_4326_30ss_V1_0" / "GHS_POP_E2020_GLOBE_R2023A_4326_30ss_V1_0.tif"
POP_SMALL = DATA / "population_2020_2.5min_40N-40S.tif"   # our shrunk copy, made once (data/ isn't in git)

if not POP_SMALL.exists():
    with rasterio.open(POP_FILE) as src:
        cell = src.res[0] * 5                                     # 5 × 30" = 2.5' cells
        transform = from_origin(src.bounds.left, 40, cell, cell)  # grid starts at the left edge, 40°N
        width = math.ceil((src.bounds.right - src.bounds.left) / cell)
        height = math.ceil(80 / cell)                             # 80° tall: 40°N down to 40°S
        shrunk = np.zeros((height, width), dtype="float64")
        reproject(source=rasterio.band(src, 1), destination=shrunk,
                  src_transform=src.transform, src_crs=src.crs,
                  dst_transform=transform, dst_crs=src.crs, resampling=Resampling.sum)
        with rasterio.open(POP_SMALL, "w", driver="GTiff", height=height, width=width, count=1,
                           dtype="float64", crs=src.crs, transform=transform, compress="lzw") as out:
            out.write(shrunk, 1)

with rasterio.open(POP_SMALL) as small:
    pop = small.read(1)                 # people per 2.5' cell, as a table of numbers (rows × columns)
    pop_transform = small.transform     # the rule that turns a row/column into a longitude/latitude

#7b · Grow a true 30 km zone around every reef piece (about 7 seconds)
# ── 7b · A 30 km zone around every reef piece ───────────────────────────────
# Degrees can't measure 30 km, so we flatten the world with the Mercator projection,
# where a circle stays a circle. Mercator stretches distances by 1/cos(latitude),
# so each piece's 30 km is stretched by the same amount. Checked: 29.8–30.0 km
# at the equator, 15° and 30°. We do the Mercator maths ourselves so longitudes
# above 180 (our 0–360 trick) aren't wrapped back round.
R = 6_378_137   # Earth's radius in metres, as Web Mercator uses

def to_mercator(coords):              # (lng, lat) in degrees → (x, y) in metres
    lng, lat = np.radians(coords[:, 0]), np.radians(coords[:, 1])
    return np.column_stack([R * lng, R * np.log(np.tan(np.pi / 4 + lat / 2))])

def from_mercator(coords):            # (x, y) in metres → (lng, lat) in degrees
    x, y = coords[:, 0] / R, coords[:, 1] / R
    return np.column_stack([np.degrees(x), np.degrees(2 * np.arctan(np.exp(y)) - np.pi / 2)])

simplified = reefs_single_pieces.geometry.simplify(0.005)            # ~500 m detail: plenty for a 30 km zone, much faster
latitudes = reefs_single_pieces.representative_point().y.to_numpy()  # each piece's latitude
flat = shapely.transform(simplified.to_numpy(), to_mercator)          # flatten all pieces at once
grown = shapely.buffer(flat, 30_000 / np.cos(np.radians(latitudes)), quad_segs=4)   # grow each by 30 km
zones = gpd.GeoSeries(shapely.transform(grown, from_mercator), crs=4326)            # back to degrees (0–360)

#7c · Put the zones back on −180…180, because that's how the population grid is laid out
# ── 7c · Undo the 0–360 trick for the population grid ───────────────────────
# Zones east of 180 slide back by −360. Zones that cross 180 are cut in two first.
b = zones.bounds
west_side = zones[b.maxx <= 180]
east_side = zones[b.minx >= 180].translate(xoff=-360)
across = zones[(b.minx < 180) & (b.maxx > 180)]
across_west = across.intersection(box(0, -90, 180, 90))
across_east = across.intersection(box(180, -90, 360, 90)).translate(xoff=-360)
zone_shapes = pd.concat([west_side, east_side, across_west, across_east])
zone_shapes = zone_shapes[~zone_shapes.is_empty]

#7d · Count the people inside the zone, per hexagon
# ── 7d · People inside the zone, added up per hexagon ──────────────────────
# "Paint" the zones onto the population grid: 1 = inside a zone, 0 = outside.
in_zone = features.rasterize(((shape, 1) for shape in zone_shapes),
                             out_shape=pop.shape, transform=pop_transform, fill=0, dtype="uint8")
rows, cols = np.nonzero((in_zone == 1) & (pop > 0))       # grid cells inside a zone with people in them
lngs, lats = rasterio.transform.xy(pop_transform, rows, cols)   # each cell's centre
people_here = pop[rows, cols]
print(f"People within 30 km of a reef: {people_here.sum() / 1e6:,.0f} million")   # about 447

# Each cell's people go to the hexagon where they LIVE (which may not contain reef itself)
cells = [h3.latlng_to_cell(lat, lng, RES) for lat, lng in zip(lats, lngs)]
people_per_hexagon = pd.Series(people_here).groupby(pd.Series(cells)).sum()
print(f"Hexagons with people near reefs: {len(people_per_hexagon):,}")            # 1,524

#7e · Draw the people layer as circles.
# ── 7e · People layer: one ring per hexagon, area ∝ people ─────────────────
# See-through rings sit on top of the reef hexagons, so you can see both at once.
# Biggest first, so the small rings end up on top and stay easy to hover.
people_layer = folium.FeatureGroup(name="People within 30 km of a reef")
biggest = people_per_hexagon.max()
for cell, people in people_per_hexagon.sort_values(ascending=False).items():
    lat, lng = h3.cell_to_latlng(cell)        # the hexagon's centre
    if lng < 0:
        lng += 360                            # same 0–360 trick as the hexagons
    folium.CircleMarker(
        location=[lat, lng],
        radius=1 + 15 * math.sqrt(people / biggest),             # sqrt: circle AREA grows with people
        color=P.SUNFLOWER, weight=1, opacity=0.9,                # a yellow ring…
        fill=True, fill_color=P.SUNFLOWER, fill_opacity=0.15,   # …with a see-through middle
        tooltip=f"{people:,.0f} people live within 30 km of a reef here",
    ).add_to(people_layer)
people_layer.add_to(m)


# ── Title ─────────────────────────────────────────────────────────────────
# TODO: add_title(m, "Title", "one-line subtitle")


add_credit(m,
    'Reefs: <a href="https://www.unep-wcmc.org">UNEP-WCMC</a>, WorldFish Centre, WRI, TNC – '
    'Global distribution of warm-water coral reefs v4.1 (released 2021) · '
    'People: <a href="https://doi.org/10.2905/2FF68A52-5B5B-4A22-8F40-C41DA8332CFE">JRC GHS-POP R2023A</a>, 2020, CC BY 4.0'
)
folium.LayerControl(collapsed=False).add_to(m)   # the on/off box: keep this LAST, after every layer
# ── Save ──────────────────────────────────────────────────────────────────
m.save(HERE / "map.html")
print("Saved", HERE / "map.html")

Doing the challenge too? Use this template for your own →