Data analysis · Intermediate · 25 min
Map data by country with GeoPandas
By Padding · Updated 18 Nov 2026
Python 3.15 · GeoPandas 1.2.0 · pandas 3.1.1 · matplotlib 3.11.2 (checked on python:3.15-slim)
You will join a table of country values to Natural Earth boundaries by ISO code, find the codes that do not match, and save a classed choropleth map of Africa in an equal-area projection with a clear no-data style.
On this page
A choropleth map colours each area by a value: one shade per country, darker for more. It is one of the most requested charts in reports about Africa, and one of the easiest to get quietly wrong. The country you forgot to join is not an error message; it is a blank shape that readers take as "zero" or do not notice at all.
In this tutorial you map a small table of values for 54 African countries with GeoPandas, which adds a geometry column to a pandas DataFrame so that each row can carry a country's outline. You load the public-domain Natural Earth boundaries, keep Africa, join your table on three-letter ISO codes and list every code that fails to match on either side. Then you sort the values into five bands, reproject to an equal-area projection so large countries are not inflated, and save the map as SVG and PNG with a hatched no-data style.
The values are made up: partner shops per 100,000 people for an imaginary payments company. The map title says so. Swap in your own table once the method works.
Step 1 · Create the project and install GeoPandas
Make a throwaway folder with a virtual environment, then install GeoPandas with the libraries it uses to read files (pyogrio), handle coordinate systems (pyproj) and work with shapes (shapely), plus matplotlib for drawing. Every package is pinned to the version this tutorial was written against:
mkdir -p ~/geopandas-demo/data ~/geopandas-demo/maps
cd ~/geopandas-demo
python3 -m venv .venv
. .venv/bin/activate
pip install "geopandas==1.2.0" "pyogrio==0.13.0" "pyproj==3.8.0" "shapely==2.2.0" \
"pandas==3.1.1" "numpy==2.5.5" "matplotlib==3.11.2"
python -c "import geopandas, pyogrio, pyproj; print(geopandas.__version__, pyogrio.__version__, pyproj.__version__)"pyogrio's wheel bundles the GDAL library, so you do not need to install GDAL from your package manager. The wheels together come to roughly 80 MB. On prepaid mobile data, run the install once on Wi-Fi: pip caches what it downloads, so the next project with the same versions installs from the cache.
Check it worked
The last line prints 1.2.0 0.13.0 3.8.0. If pip starts compiling pyogrio from source instead, there is no wheel for your Python version or platform; move to a supported Python release rather than installing GDAL by hand.
Step 2 · Download a pinned copy of the boundaries
Natural Earth publishes country boundaries at three scales. The 1:110m file is about 0.8 MB and detailed enough for a map of a whole continent. Download it from the project's tagged v5.1.2 release, not from a "latest" link, so the shapes and codes never change under you, and check its SHA-256 hash:
cd ~/geopandas-demo
. .venv/bin/activate
cat > fetch_boundaries.py <<'PY'
import hashlib
import urllib.request
from pathlib import Path
URL = (
"https://raw.githubusercontent.com/nvkelso/natural-earth-vector/"
"v5.1.2/geojson/ne_110m_admin_0_countries.geojson"
)
SHA256 = "6866c877d39cba9c357620878839b336d569f8c662d3cfab4cb1dbe2d39c977f"
target = Path("data/ne_110m_admin_0_countries.geojson")
if not target.exists():
urllib.request.urlretrieve(URL, target)
digest = hashlib.sha256(target.read_bytes()).hexdigest()
print(f"{target.name}: {target.stat().st_size / 1024:.0f} KB")
print("hash ok" if digest == SHA256 else f"hash MISMATCH: {digest}")
PY
python fetch_boundaries.pyThe script uses only Python's standard library, so it works the same on Linux, macOS and Windows. Natural Earth data is in the public domain: you can publish maps made from it without asking or crediting, though a source line helps your readers.
Check it worked
The script prints ne_110m_admin_0_countries.geojson: 819 KB and hash ok. A mismatch means the download was cut short or changed; delete the file in data/ and run the script again.
Step 3 · Load the shapes and keep Africa
geopandas.read_file returns a GeoDataFrame: a DataFrame whose geometry column holds one polygon or multipolygon per row. Load the world, check its coordinate reference system (CRS), filter on the CONTINENT column and look at the code columns:
cd ~/geopandas-demo
. .venv/bin/activate
cat > explore.py <<'PY'
import geopandas as gpd
world = gpd.read_file("data/ne_110m_admin_0_countries.geojson")
print("countries:", len(world))
print("crs:", world.crs.to_string())
africa = world[world["CONTINENT"] == "Africa"]
print("africa:", len(africa))
codes = africa[["NAME", "ADM0_A3", "ISO_A3"]]
print(codes[codes["ADM0_A3"] != codes["ISO_A3"]].to_string(index=False))
PY
python explore.py > explore.txt
cat explore.txtEPSG:4326 means the coordinates are plain longitude and latitude in degrees. That is fine for storing shapes and wrong for measuring them, which matters in a later step.
The file has several code columns. ADM0_A3 is Natural Earth's own code and ISO_A3 is the ISO 3166-1 alpha-3 code that most statistical tables use. They differ for a few places, so join on ISO_A3. Somaliland has no ISO code of its own and carries -99, Natural Earth's marker for "no code".
Check it worked
You see countries: 177, crs: EPSG:4326 and africa: 51, then three rows where the codes differ: W. Sahara (SAH against ESH), Somaliland (SOL against -99) and S. Sudan (SDS against SSD).
Step 4 · Join your table and find the codes that differ
Create the table of values. It uses ISO codes, as most published datasets do, and leaves two values empty where there was no survey. Save it as UTF-8 so names such as Côte d'Ivoire and São Tomé and Príncipe survive; when a table comes from a spreadsheet in French or Portuguese, a wrong encoding is the usual cause of mangled names.
cd ~/geopandas-demo
cat > data/partner_shops.csv <<'CSV'
iso3,country,shops_per_100k
DZA,Algeria,8.4
AGO,Angola,6.1
BEN,Benin,14.2
BWA,Botswana,22.5
BFA,Burkina Faso,11.8
BDI,Burundi,3.9
CPV,Cabo Verde,31.0
CMR,Cameroon,12.6
CAF,Central African Republic,1.7
TCD,Chad,2.8
COM,Comoros,9.5
COG,Congo,7.3
ZAR,DR Congo,4.4
CIV,Côte d'Ivoire,19.7
DJI,Djibouti,10.2
EGY,Egypt,16.9
GNQ,Equatorial Guinea,5.6
ERI,Eritrea,
SWZ,Eswatini,18.3
ETH,Ethiopia,6.8
GAB,Gabon,13.1
GMB,Gambia,15.4
GHA,Ghana,41.6
GIN,Guinea,9.1
GNB,Guinea-Bissau,4.9
KEN,Kenya,63.2
LSO,Lesotho,17.5
LBR,Liberia,7.7
LBY,Libya,
MDG,Madagascar,5.2
MWI,Malawi,12.0
MLI,Mali,10.6
MRT,Mauritania,6.4
MUS,Mauritius,28.8
MAR,Morocco,24.1
MOZ,Mozambique,9.8
NAM,Namibia,21.3
NER,Niger,3.2
NGA,Nigeria,36.5
RWA,Rwanda,44.0
STP,São Tomé and Príncipe,8.9
SEN,Senegal,27.4
SYC,Seychelles,33.6
SLE,Sierra Leone,8.0
SOM,Somalia,11.2
ZAF,South Africa,38.9
SSD,South Sudan,1.9
SDN,Sudan,4.1
TZA,Tanzania,47.3
TGO,Togo,13.7
TUN,Tunisia,20.6
UGA,Uganda,52.8
ZMB,Zambia,16.1
ZWE,Zimbabwe,14.9
CSVBefore the real join, run an outer merge with indicator=True. It keeps every row from both sides and adds a _merge column saying where each row came from, so nothing can go missing without you seeing it:
cd ~/geopandas-demo
. .venv/bin/activate
cat > join_check.py <<'PY'
import geopandas as gpd
import pandas as pd
world = gpd.read_file("data/ne_110m_admin_0_countries.geojson")
africa = world[world["CONTINENT"] == "Africa"]
values = pd.read_csv("data/partner_shops.csv", encoding="utf-8")
print("table rows:", len(values), "missing values:", values["shops_per_100k"].isna().sum())
check = africa[["NAME", "ISO_A3"]].merge(
values, left_on="ISO_A3", right_on="iso3", how="outer", indicator=True
)
print(check["_merge"].value_counts().to_string())
print("\nIn the table, no shape:")
print(check.loc[check["_merge"] == "right_only", ["iso3", "country"]].to_string(index=False))
print("\nOn the map, no table row:")
print(check.loc[check["_merge"] == "left_only", ["NAME", "ISO_A3"]].to_string(index=False))
PY
python join_check.py > join_check.txt
cat join_check.txtEach unmatched code has a different cause, and each needs a different fix:
- ZAR and COD are the same country. ZAR is Zaire's old code, replaced by COD in ISO 3166; older datasets still use it. Recode it.
- CPV, COM, MUS, STP and SYC are island states too small to appear in the 1:110m file. Nothing is wrong with the codes. Mention them in a note under the map, or use the 1:10m file if they must show.
- ESH and -99 are Western Sahara and Somaliland, whose status is disputed. Your table has no row for them, which is common. Keep their shapes and draw them as no data.
Check it worked
You see table rows: 54 missing values: 2, then both 48, right_only 6 and left_only 3. The first list has COM, CPV, MUS, STP, SYC and ZAR; the second has Somaliland, Dem. Rep. Congo and W. Sahara.
Step 5 · Make the join repeatable and band the values
Put the loading, recoding and joining in one module that the next scripts import. Join with how="left" from the shapes, so every country outline stays on the map whether or not it has a value, and validate="one_to_one" so a duplicated code in either table raises an error instead of doubling a country.
Then sort the values into bands with pd.cut. A continuous colour scale makes readers compare shades they cannot tell apart; five bands with round edges let them read a value from the legend. The breaks here double each time (5, 10, 20, 40), which suits data where most countries are low and a few are much higher. right=False puts a value of exactly 10 into "10 to 20", not "5 to 10".
cd ~/geopandas-demo
. .venv/bin/activate
cat > africa.py <<'PY'
import geopandas as gpd
import pandas as pd
# Codes in our table that differ from ISO 3166-1 alpha-3 as Natural Earth uses it.
RECODE = {"ZAR": "COD"} # Zaire's old code, still found in older datasets
BREAKS = [0, 5, 10, 20, 40, float("inf")]
LABELS = ["under 5", "5 to 10", "10 to 20", "20 to 40", "40 or more"]
def load_africa():
world = gpd.read_file("data/ne_110m_admin_0_countries.geojson")
africa = world.loc[world["CONTINENT"] == "Africa", ["NAME", "ISO_A3", "geometry"]]
return africa.reset_index(drop=True)
def load_values():
values = pd.read_csv("data/partner_shops.csv", encoding="utf-8")
values["iso3"] = values["iso3"].replace(RECODE)
return values
def load_joined():
africa = load_africa()
values = load_values()
joined = africa.merge(
values, left_on="ISO_A3", right_on="iso3", how="left", validate="one_to_one"
)
joined["band"] = pd.cut(
joined["shops_per_100k"], bins=BREAKS, labels=LABELS, right=False
)
return joined
PY
cat > bands.py <<'PY'
from africa import load_joined
joined = load_joined()
print("shapes:", len(joined))
print("no value:", ", ".join(sorted(joined.loc[joined["shops_per_100k"].isna(), "NAME"])))
print(joined["band"].value_counts(sort=False, dropna=False).to_string())
PY
python bands.py > bands.txt
cat bands.txtCalling africa.merge(...) on the GeoDataFrame keeps the result a GeoDataFrame. If you write it the other way round, values.merge(africa, ...), you get a plain DataFrame and lose the map methods.
Check it worked
You see shapes: 51, so no country was dropped or doubled, and no value: Eritrea, Libya, Somaliland, W. Sahara: DR Congo has its value now. The band counts are 8, 11, 16, 7 and 5, with 4 under NaN.
Step 6 · Pick a projection that keeps areas honest
A choropleth asks the eye to compare coloured areas, so the projection should keep areas in proportion. Web Mercator (EPSG:3857, the projection of most web maps) stretches land away from the equator. Africa straddles the equator, so the distortion is smaller than for Europe, but its north and south still grow. An equal-area projection centred on the continent avoids that. ESRI:102022 is Africa Albers Equal Area Conic, and pyproj knows it by that code.
Compare the two by measuring a few countries:
cd ~/geopandas-demo
. .venv/bin/activate
cat > project.py <<'PY'
from africa import load_africa
africa = load_africa().set_index("NAME")
equal_area = africa.to_crs("ESRI:102022")
mercator = africa.to_crs("EPSG:3857")
print("projected crs:", equal_area.crs.name)
print(f"{'country':<16}{'equal-area km2':>16}{'Mercator km2':>16}")
for name in ["Algeria", "Dem. Rep. Congo", "Nigeria", "South Africa", "Rwanda"]:
true_km2 = equal_area.area[name] / 1e6
merc_km2 = mercator.area[name] / 1e6
print(f"{name:<16}{true_km2:>16,.0f}{merc_km2:>16,.0f}")
PY
python project.py > project.txt
cat project.txtBoth projections use metres, so .area / 1e6 gives square kilometres. Never call .area on the original longitude and latitude data: the result is in square degrees, which mean nothing, and GeoPandas warns you if you try.
Check it worked
The table shows Algeria and DR Congo at about 2.3 million km² each in the equal-area projection, but Algeria at about 3.0 million km² in Mercator, around 30% larger than it should be, while DR Congo on the equator barely changes. South Africa grows by a similar share. The equal-area figures sit within a few per cent of official areas; the gap comes from the simplified 1:110m outlines.
Step 7 · Draw and save the map
Now draw the map. categorical=True treats the band column as named classes and colours them in order, palest first. missing_kwds styles the four countries with no value: a white fill with grey hatching, which stays distinct from the palest band even in greyscale print or for readers with colour-vision deficiency.
Build the legend yourself rather than with legend=True. GeoPandas draws each legend key for a categorical map as a small round marker with no outline, so the "No data" key would be a white dot on a white page: a label next to empty space. One Patch per band, plus one with the same white fill, grey edge and hatching as the map, gives square swatches that match what the reader sees on the countries. Taking the five colours from the colour map once, and passing them to both the map and the legend, keeps the two in step.
The small grey line at the bottom states the boundary source. fig.supxlabel places it under the map, and the constrained layout reserves room for it, so the legend cannot sit on top of it. Natural Earth draws boundaries as they are in practice on the ground (de facto), and shows Western Sahara and Somaliland as separate shapes. Governments and organisations disagree about some of these borders, and some publications must follow one country's official view. Since v5.0, Natural Earth also publishes "point of view" editions of its 1:10m country boundaries for a few dozen countries and organisations for exactly this reason (see its disputed boundaries policy). Check which one your publisher or client requires before you share the map, and say in the note which you used.
cd ~/geopandas-demo
. .venv/bin/activate
cat > draw_map.py <<'PY'
import matplotlib
matplotlib.use("Agg")
matplotlib.rcParams["svg.fonttype"] = "none" # keep text as text in the SVG
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.patches import Patch
from africa import LABELS, load_joined
joined = load_joined().to_crs("ESRI:102022")
# One colour per band, palest first, taken from the YlGnBu colour map.
band_colours = matplotlib.colormaps["YlGnBu"].resampled(len(LABELS))(range(len(LABELS)))
no_data = {"facecolor": "#ffffff", "edgecolor": "#6a707b", "hatch": "///"}
fig, ax = plt.subplots(figsize=(8, 8.5), layout="constrained")
joined.plot(
column="band",
categorical=True,
cmap=ListedColormap(band_colours),
linewidth=0.4,
edgecolor="#2a2d33",
missing_kwds=no_data,
ax=ax,
)
handles = [
Patch(facecolor=colour, edgecolor="#2a2d33", linewidth=0.4, label=label)
for colour, label in zip(band_colours, LABELS)
]
handles.append(Patch(**no_data, linewidth=0.4, label="No data"))
ax.legend(handles=handles, title="Shops per 100,000 people", loc="lower left", frameon=False)
ax.set_title("Partner shops per 100,000 people (made-up data)", loc="left", fontsize=13)
ax.set_axis_off()
fig.supxlabel(
"Boundaries: Natural Earth 1:110m, v5.1.2. Borders shown are de facto and not an endorsement.",
x=0.01, ha="left", fontsize=7, color="#6a707b",
)
fig.savefig("maps/africa_shops.svg")
fig.savefig("maps/africa_shops.png", dpi=150)
print("saved:", "maps/africa_shops.svg", "maps/africa_shops.png")
PY
cat > check_png.py <<'PY'
import struct
import sys
with open(sys.argv[1], "rb") as f:
head = f.read(24)
print("png signature:", head[:8] == b"\x89PNG\r\n\x1a\n")
print("size: %d x %d px" % struct.unpack(">II", head[16:24]))
PY
python draw_map.py
python check_png.py maps/africa_shops.png
ls -l mapsmatplotlib.use("Agg") draws without a screen, so the script runs on a server or in a scheduled job. The SVG keeps its text as text, so the title and legend stay searchable and sharp. It is also a fair size for the web: on a page read on a low-end Android phone over prepaid data, it is usually the lighter of the two files.
Check it worked
The script prints saved: maps/africa_shops.svg maps/africa_shops.png, then png signature: True and size: 1200 x 1275 px. Open maps/africa_shops.svg in a browser. Kenya, Uganda, Tanzania, Rwanda and Ghana are in the darkest navy band; Libya, Eritrea, Western Sahara and Somaliland are white with grey diagonal hatching; and Madagascar sits fully inside the frame. In the bottom-left legend, the five bands are square swatches from pale yellow to navy, and the last key, "No data", is a white square with a grey outline and the same hatching as the countries. The grey source line sits below the legend, clear of it.
When you are done, delete the project with rm -rf ~/geopandas-demo.
Next steps
- Join DataFrames in pandas without losing rows goes deeper into join types, the indicator column and
validate. - Choose the right chart for your data helps you decide when a map is the right answer and when a sorted bar chart says the same thing more clearly.
- Plot data with matplotlib's figure and axes interface covers the figure, axes and export settings this map is built on.
- Chart the energy data with small multiples shows how to compare many countries side by side when one map is not enough.
Part of these paths
Related tutorials
- Join DataFrames in pandas without losing or duplicating rowsYou will join orders to customers and products with pandas merge, compare the four join types by row count, catch duplicate and mismatched keys with validate= and indicator=, list unmatched rows with an anti-join and stack new batches with concat.
- Choose the right chart for your data and keep it honestYou will match five common questions to the chart that answers each one, then redraw four misleading charts in matplotlib 3.11 (a truncated bar axis, dual axes, rainbow colours and a tilted pie) as honest versions with direct labels, a colour-blind-safe palette, a source line and written alt text, saved as SVG and 2x PNG.
- Plot data with matplotlib's figure and axes interfaceYou will draw line, bar, scatter and histogram charts with matplotlib's figure and axes interface, format their ticks as thousands, percentages and dates, annotate the busiest day, combine all four in one grid and save it as SVG and as a sharp 2x PNG.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials