WorldPop — age/sex population pyramid (live)¶
WorldPop publishes gridded population estimates broken down by age and
sex. This notebook pulls the age_structures product for Comoros 2020 —
36 cohort rasters plus a tidy per-cohort table — and plots the classic
population pyramid from the table.
What this notebook does¶
- Download the
age_structuresproduct for Comoros (ISOCOM) 2020. WorldPop is a file-writing backend, sodownload()mosaics/crops the cohort rasters to the AOI and writes them — plus a tidy CSV — to disk. - Pyramid — read the CSV back, pivot it to age band × sex, and draw a left/right population pyramid with matplotlib.
WorldPop is open (CC-BY-4.0) and needs no credentials.
Setup¶
The imports for the whole notebook in one place. EarthLens is the
unified entry point; pandas reads the tidy table back; matplotlib draws
the pyramid (the Agg backend keeps it headless-safe). We also make a
scratch directory for the downloaded rasters and CSV.
import tempfile
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
from earthlens.earthlens import EarthLens
scratch_dir = tempfile.mkdtemp()
1 · Download the age/sex population¶
Build the request¶
We describe what we want — the age_structures product, the Comoros AOI
(ISO code COM plus an explicit lat/lon box), and the 2020 epoch — in a
single EarthLens(...) constructor, kept on its own line so the download
step that follows reads cleanly.
worldpop = EarthLens(
data_source='worldpop',
variables=['age_structures'],
aoi='COM',
start='2020',
end='2020',
fmt='%Y',
lat_lim=[-12.5, -11.3],
lon_lim=[43.2, 44.6],
path=scratch_dir,
)
Fetch the cohort rasters and table¶
download() mosaics and crops the 36 cohort rasters to the AOI, writes
them to the scratch directory, and returns the list of written paths.
paths = worldpop.download(progress_bar=False)
Read the tidy table¶
One of the written paths is a tidy CSV with one row per age/sex cohort.
We pick it out of the returned paths first, then read it into a
DataFrame.
csv_paths = [p for p in paths if str(p).endswith('.csv')]
csv = csv_paths[0]
df = pd.read_csv(csv)
df.head()
2 · Population pyramid¶
Pivot the tidy table to age band × sex, then draw the two halves of the pyramid: males extend left (negated), females right, with each bar placed at its age band's lower bound.
piv = df.pivot_table(
index='age_low', columns='sex', values='population', aggfunc='sum'
).sort_index()
fig, ax = plt.subplots(figsize=(5, 5))
ax.barh(piv.index, -piv['m'], height=4, label='male')
ax.barh(piv.index, piv['f'], height=4, label='female')
ax.set_xlabel('population')
ax.set_ylabel('age band (lower bound)')
ax.set_title('Comoros 2020 population pyramid')
ax.legend()
plt.tight_layout()
plt.show()