popgrid
Tiled grid maps for Python, land area and population, clearly explained.
popgrid turns a country (or any set of regions) into a block cartogram where every block is an equal share of the whole: 0.1% of the national land area, or 0.1% of the population. Same regions, same colours, two ways of seeing them. Where land and people diverge is the whole point.
Madrid is a sliver of land and a giant of population. The empty interior shrinks; the coasts and the capital swell. A block on the left is the same size as a block on the right, so the comparison is literally true.
Install
pip install popgrid
Requires Python 3.10+. Country boundaries are downloaded once from Natural Earth and cached locally; population data for the bundled countries ships with the package.
Quickstart
from popgrid import PopGrid, AreaGrid
# Population: every block = 0.1% of the national population
PopGrid("ESP").plot().savefig("spain_population.png", dpi=170, bbox_inches="tight")
# Land area: every block = 0.1% of the national land area
AreaGrid("ESP").plot().savefig("spain_area.png", dpi=170, bbox_inches="tight")
| Population | Land area |
|---|---|
.plot() builds the grid on first call and returns a Matplotlib figure, so you can save, show, or restyle it however you like.
Your own data
Both classes accept any GeoDataFrame through from_geodataframe, so popgrid is not limited to the bundled countries. Point it at a shapefile, a GeoJSON, or a PostGIS query.
AreaGrid.from_geodataframe(gdf, region_col=...)sizes each region by its land area.PopGrid.from_geodataframe(gdf, region_col=..., weight_col=...)sizes each region by a numeric column you supply, such as population.
import geopandas as gpd
from popgrid import AreaGrid, PopGrid
gdf = gpd.read_file("examples/data/barcelona_districts.geojson")
# Sized by district land area
AreaGrid.from_geodataframe(gdf, region_col="district").plot(
title="Land Area of Barcelona",
subtitle="Every block = 0.1% of city land area",
)
# Sized by your own population column
PopGrid.from_geodataframe(gdf, region_col="district", weight_col="population").plot(
title="Population of Barcelona",
subtitle="Every block = 0.1% of city population",
)
Barcelona's 10 districts, built entirely from a custom GeoDataFrame. Eixample, the densest district, balloons under population; Les Corts and the green hills of Sarrià shrink.
| Land area | Population |
|---|---|
A full runnable version is in examples/barcelona.py, using the district boundaries in examples/data/barcelona_districts.geojson.
Use with matplotlib
.plot() gives you a finished figure. .draw(ax) gives you just the map, inside an Axes you already own, so popgrid fits into any layout: a row of countries, a map beside a chart, your own title block.
import matplotlib.pyplot as plt
from popgrid import AreaGrid, PopGrid
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))
AreaGrid("ESP").draw(ax1, background_style="none")
PopGrid("ESP").draw(ax2, background_style="none")
ax1.set_title("Land area")
ax2.set_title("Population")
draw returns the Axes, sets its aspect to equal and turns the axis off. It draws the main landmass and nearby islands; distant territories (Canary Islands, Hawaii, overseas France) need their own Axes, which is what plot() arranges for you.
Styling
Both plot() and draw() take a style dict. Leave a key out and it keeps its automatic value.
| Key | Default | What it controls |
|---|---|---|
edge_color |
#000000 |
Region outline colour |
edge_width |
auto | Outline width in points (auto: 8% of a block) |
grid_color |
auto | Background grid lines or tiles |
grid_width |
0.35 |
Grid line width in points |
cell_gap |
auto | Gap between blocks, as a fraction of a block |
label_color |
auto | Label text colour (auto: black or white by region luminance) |
label_size |
auto | Fixed label size in points (auto: fit each region) |
label_min_size, label_max_size |
7, 18 |
Bounds for auto-fitted labels |
label_weight, label_font |
bold, default |
Label font |
PopGrid("DEU", color_map={"Bayern": "#1A3829"}).plot(
style={"edge_color": "#1A3829", "edge_width": 1.0, "label_max_size": 22},
label_mode="auto",
labels={"Baden-Württemberg": "BaWü"},
)
color_map pins regions to colours; the rest keep their automatic, adjacency-aware palette colour. exclude=[...] drops regions before the grid is built (they take no blocks); countries come with a short default list of uninhabited specks, and --exclude adds to it on the CLI. label_mode is auto (fit the full name, else wrap it on two lines, else abbreviate), full, short or none. labels overrides individual names; an empty string hides one.
Command line
generate.py (at the repo root) renders one or many countries from the terminal.
# Population map of Spain
python generate.py ESP --mode pop
# Land-area map
python generate.py ESP --mode area
# Side-by-side comparison (land area vs population, equal block size)
python generate.py ESP --mode compare
# Several countries at once, into a folder
python generate.py ESP DEU FRA --mode compare --out compare/
# The 24 countries with curated census data
python generate.py ALL --mode pop
# Every supported country
python generate.py WORLD --mode compare --out world/
Useful flags: --n (target block count, default 1000), --mainland (drop detached territories), --no-panels (keep nearby islands inline, drop distant panels), --palette, --dissolve, --label-mode auto|full|short|none, --label-size, --edge-color, --edge-width, --grid-color, --bg, --background grid|solid|none, --title, --subtitle, --source, --dpi, --out. Run python generate.py --help for the full list.
ArcGIS Online
The optional helpers in popgrid.arcgis publish popgrid blocks to ArcGIS Online as Hosted Feature Layers. The ArcGIS dependency is not required for normal popgrid usage; it is imported only by the publishing helpers.
Install the optional publishing dependencies:
pip install "popgrid[arcgis]"
Create an ArcGIS API for Python profile:
from getpass import getpass
from arcgis.gis import GIS
# Saves an encrypted profile once; the password is never written in your code
GIS("https://www.arcgis.com", "YOUR_USERNAME", getpass(), profile="popgrid_agol")
Preview the output locally without publishing:
python examples/publish_arcgis_online.py ESP --n 200 --mode both --dry-run
Publish area and population as separate Hosted Feature Layers:
python examples/publish_arcgis_online.py ESP --n 1000 --mode both --profile popgrid_agol --folder PopGrid
When --mode both is used, two services are created so the undeformed land-area grid and the population-adjusted grid do not overlap in the same Feature Service:
popgrid_ESP_area_n1000
popgrid_ESP_population_n1000
Each layer is published with region-based symbology from popgrid's color_hex values. To reapply that symbology to an existing layer:
python examples/style_arcgis_layer.py --profile popgrid_agol --title popgrid_ESP_population_n1000
The published attributes include iso3, mode, block_id, region, color_hex, target_n, blocks, share_pct, cell_km, land_id, cx, and cy.
Countries
Any country works: PopGrid("CHL"), PopGrid("IND"), PopGrid("NGA"). Boundaries come from Natural Earth admin-1 and population from one of two bundled tables:
- Curated census figures for 24 countries, at the level the map shows (autonomous communities for Spain, Länder for Germany, and so on):
ARGAUSBELBRACANCHECHNDEUESPFRAGBRITAJPNKORMEXNLDNORPHLPOLPRTSWETURUSAZAF - GHS-POP 2025 estimates for everything else: the JRC's 1 km gridded population summed over every Natural Earth admin-1 polygon on Earth. Modelled, not census; within a few percent of official regional figures, and always consistent with the polygon being drawn.
popgrid.supported_countries() lists the 207 countries with enough regions to make a map; popgrid.bundled_countries() the 24 curated ones. python generate.py WORLD --mode compare renders all of them.
For sub-national data such as cities, or to use your own population numbers, use from_geodataframe with your own polygons.
How it works
- Load admin-1 regions, project to an equal-area CRS, and choose a cell size so the country tiles into roughly
nblocks (default 1000, so one block ≈ 0.1%). - Allocate an integer block quota per region using the Hamilton (largest-remainder) method, weighted by area or population.
- For population maps, deform each landmass with a contiguous-area cartogram so a region's area tracks its population, then rasterise the deformed shapes onto the grid. Dense regions bulge, sparse regions pinch, relative position and silhouette are preserved. Two engines: a rubber-sheet cartogram (Dougenik et al.) by default, and a diffusion cartogram (Gastner-Newman) that
engine="auto"switches to when the sheet would tear, which happens for countries with an empty interior such as China or Canada. Passengine="diffusion"to use it everywhere. - Fit each region to its exact quota and assign stable colours from the geographic adjacency graph, so the same region keeps the same colour across the area and population maps.
Notes and limitations
- Population currency. Bundled population figures are a fixed snapshot, not live data. For up-to-date or custom numbers, pass your own values through
PopGrid.from_geodataframe(..., weight_col=...). - Disputed borders. Natural Earth draws them its own way (Kashmir, Crimea, Western Sahara). Check before publishing a map of a contested region.
- Block counts land close to
nbut not always exactly, because of quota rounding and edge fitting (e.g. 984 or 1018 rather than 1000).
Data sources
- Country and admin-1 boundaries: Natural Earth (
ne_10m_admin_1_states_provinces), public domain. - Curated population figures: national statistical offices (see the
sourcecolumn ofpopulation.csv). - Fallback population figures: GHS-POP R2023A, epoch 2025, European Commission JRC, summed over Natural Earth admin-1 polygons.
- Barcelona example: district boundaries from Ajuntament de Barcelona open data; population from the 2023 municipal register.
License & credits
MIT licensed. Built by Josep Ferrer at databites.tech, data and AI, clearly explained through diagrams.
The block-cartogram format is inspired by the "Population of X, Visualised" maps popularised by @Civixplorer.
Metadata
Release files for popgrid 0.6.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| popgrid-0.6.0.tar.gz | 165.5 kB | Without provenance | Details for popgrid-0.6.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| popgrid-0.6.0-py3-none-any.whl | Python 3 | none | any | Details for popgrid-0.6.0-py3-none-any.whl |
Total release size: 319.1 kB
Release files / popgrid-0.6.0.tar.gz
| Download URL | popgrid-0.6.0.tar.gz |
|---|---|
| Size | 165.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e01c7e35dd1cf2cbb4a18d516cbd5b7deb0cd92e5d900deb4a4a4e36e388241f
|
|
BLAKE2b-256 checksum How to use checksums |
e9b91d3724673d0935c2f2fc886a2f0149a1c465ffe6e4b49fea139cb55e25fa
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.10.11
|
Release files / popgrid-0.6.0-py3-none-any.whl
| Download URL | popgrid-0.6.0-py3-none-any.whl |
|---|---|
| Size | 153.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
7247894e5d5a3b8f9befa438997e67ab2625477c8c9ec80d58531e2a45305aed
|
|
BLAKE2b-256 checksum How to use checksums |
79f7c1059c533625df1ac9d591e6fd0bc7465757181a6400049f1ea78ab06bc6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.10.11
|
Security for popgrid 0.6.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.