How to Create a Choropleth Map in Python with GeoPandas
On this page
Problem statement
A choropleth colours each area by a value β density by district, unemployment by region β and in GeoPandas the drawing is one argument, plot(column="density"). The map's message is decided before and around that call: whether the values joined to every area, which classification turns values into colours, and what happens to the areas with no value. Each of those can change what a reader sees without changing a single number.
This page maps Germany's 401 districts and 38 regions from Eurostat and measures each decision: a boundary vintage that leaves seven districts blank, three classification schemes that tell three different stories, a "natural breaks" legend that changes between runs β and, when the colours look wrong, the outlier, the off-centre diverging ramp and the vmin that cause it.
Quick answer
If your polygon layer already contains the numeric column you want to map, the shortest workflow is:
import geopandas as gpd
import matplotlib.pyplot as plt
gdf = gpd.read_file("data/de_districts.shp")
ax = gdf.plot(
column="density",
cmap="OrRd",
legend=True,
figsize=(10, 8),
edgecolor="black",
linewidth=0.3
)
ax.set_title("Population Density by District")
ax.set_axis_off()
plt.show()
print(len(gdf), "districts, density", gdf["density"].min(), "to", gdf["density"].max(), "people/kmΒ²")
401 districts, density 35.1 to 4828.6 people/kmΒ²
That is the whole drawing. The rest of this page is about the decisions that make it say the right thing.
Load polygons, check the column, plot, classify, save
Load polygon data into a GeoDataFrame
GeoPandas can read shapefiles, GeoJSON, and many other GIS formats through read_file().
import geopandas as gpd
gdf = gpd.read_file("data/de_nuts3.gpkg")
print(gdf[["NUTS_ID", "NAME_LATN", "density"]].head(3))
print(gdf.geom_type.value_counts().to_dict())
print(gdf.crs)
NUTS_ID NAME_LATN density
0 DE254 NΓΌrnberg, Kreisfreie Stadt 2854.4
1 DE255 Schwabach, Kreisfreie Stadt 997.9
2 DE256 Ansbach, Landkreis 95.1
{'MultiPolygon': 401}
EPSG:3035
Check that the geometry type is Polygon or MultiPolygon. A choropleth map is designed for area features, not points.
If your layer contains mixed geometry types, filter to polygons before plotting:
gdf = gdf[gdf.geom_type.isin(["Polygon", "MultiPolygon"])].copy()
If you are working with a shapefile:
gdf = gpd.read_file("data/de_districts.shp")
Check the attribute column you want to map
Before plotting, inspect the available fields and confirm the target column is numeric.
print(list(gdf.columns))
print(gdf["density"].dtype)
print(gdf["density"].describe().round(1).to_dict())
['NUTS_ID', 'NAME_LATN', 'density', 'gdp_per_head', 'geometry']
float64
{'count': 394.0, 'mean': 557.0, 'std': 732.8, 'min': 35.1, '25%': 117.8, '50%': 209.6, '75%': 725.1, 'max': 4828.6}
The count is 394 of 401: seven districts have no density. They are all in Thuringia, whose districts were redrawn after the 2021 NUTS boundaries this map uses, so the 2024 figures carry codes the 2021 geometry does not have. A join on a code is only as good as the two vintages agreeing.
If the values are stored as text, convert them with pandas:
import pandas as pd
gdf["density"] = pd.to_numeric(gdf["density"], errors="coerce")
Using errors="coerce" turns invalid values into NaN, which you can handle later.
Create a basic choropleth map
The core GeoPandas choropleth workflow uses plot() with the column argument.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10, 8))
gdf.plot(
column="density",
ax=ax,
legend=True
)
plt.show()
This colors each polygon according to the value in density.
Improve the map styling
A default plot works, but it is usually better to control color, borders, title, and axes.
fig, ax = plt.subplots(figsize=(10, 8))
gdf.plot(
column="density",
ax=ax,
cmap="YlGnBu",
legend=True,
edgecolor="black",
linewidth=0.2
)
ax.set_title("Population Density by Administrative Area", fontsize=14)
ax.set_axis_off()
plt.show()
A sequential colormap such as OrRd or YlGnBu suits a value that only goes up; a diverging one needs a meaningful midpoint.
Handle missing values
Missing values often appear as blank polygons unless you define a missing-data style.
fig, ax = plt.subplots(figsize=(10, 8))
gdf.plot(
column="density",
ax=ax,
cmap="YlGnBu",
legend=True,
edgecolor="black",
linewidth=0.2,
missing_kwds={
"color": "lightgrey",
"edgecolor": "red",
"hatch": "///",
"label": "Missing values"
}
)
ax.set_title("Population Density by Administrative Area")
ax.set_axis_off()
plt.show()
You can also remove records with null values before plotting:
gdf_clean = gdf[gdf["density"].notna()].copy()
print(len(gdf), "->", len(gdf_clean), "districts;", sorted(gdf.loc[gdf["density"].isna(), "NAME_LATN"]))
401 -> 394 districts; ['Eisenach, Kreisfreie Stadt', 'Ilm-Kreis', 'Saalfeld-Rudolstadt', 'Schmalkalden-Meiningen', 'Sonneberg', 'Suhl, Kreisfreie Stadt', 'Wartburgkreis']
Dropping them leaves a hole in Thuringia with no explanation; missing_kwds keeps the hole and labels it.
Classify values for clearer interpretation
A continuous scale is not always the best choice. If values are unevenly distributed, classified ranges are easier to read.
GeoPandas supports classification schemes through the scheme argument. This requires the optional mapclassify package.
Install it if needed:
pip install mapclassify
Then use a classification method such as quantiles:
fig, ax = plt.subplots(figsize=(10, 8))
gdf.plot(
column="density",
ax=ax,
cmap="OrRd",
legend=True,
scheme="quantiles",
k=5,
edgecolor="black",
linewidth=0.2
)
ax.set_title("Population Density by Quantile Class")
ax.set_axis_off()
plt.show()
How many districts each scheme puts in each class decides what the map says:
import mapclassify
values = gdf["density"].dropna()
for name in ("EqualInterval", "Quantiles", "FisherJenks"):
c = getattr(mapclassify, name)(values, k=5)
print(f"{name:14} counts {c.counts.tolist()} upper bounds {[round(b) for b in c.bins]}")
top = mapclassify.EqualInterval(values, k=5).bins[-2]
print("darkest equal-interval class:", sorted(gdf.loc[gdf["density"] > top, "NAME_LATN"]))
EqualInterval counts [315, 53, 19, 5, 2] upper bounds [994, 1952, 2911, 3870, 4829]
Quantiles counts [79, 79, 78, 79, 79] upper bounds [107, 162, 301, 973, 4829]
FisherJenks counts [256, 60, 52, 24, 2] upper bounds [386, 998, 1905, 3073, 4829]
darkest equal-interval class: ['Berlin', 'MΓΌnchen, Kreisfreie Stadt']
Equal intervals put 315 of 394 districts in the lightest class and two β Berlin and Munich β in the darkest: a map of Germany that is pale everywhere except two cities. Quantiles give every class about 79 districts, at the price of putting 301 and 973 people/kmΒ² in neighbouring classes. Fisher-Jenks finds the gaps in the data instead.
natural_breaks is k-means with random starting points, so two runs can give two legends (Example 3). What each scheme assumes is the subject of choropleth classification explained.
When the colours look wrong
| What you see | Cause | Fix |
|---|---|---|
| one colour, a few extremes | no scheme, and an outlier | scheme="quantiles", or clip |
| everything in class 1 | equal_interval on skewed data |
scheme="quantiles" |
| colours in no order | the column is text, not a number | pd.to_numeric(...) |
| high values look pale | reversed colormap | cmap="OrRd", not "OrRd_r" |
| holes in the map | nulls not drawn | missing_kwds={...} |
| neutral colour is not at zero | asymmetric diverging range | vmin=-lim, vmax=lim |
| the pattern follows population | mapping a count, not a rate | divide by a denominator |
The continuous default stretches the ramp linearly from the minimum to the maximum, so one extreme value compresses everything else into a sliver of it. A diverging ramp puts its neutral colour at the midpoint of the range, which is zero only by coincidence. And vmin/vmax mean something different once a scheme is set. All three, measured on the districts:
import numpy as np
v = gdf["density"].dropna()
print(f"density: p95 {v.quantile(0.95):,.0f}, max {v.max():,.0f} β 95% of districts share "
f"{v.quantile(0.95) / v.max():.0%} of a continuous ramp")
gdf["gdp_vs_median"] = (gdf["gdp_per_head"] / gdf["gdp_per_head"].median() - 1) * 100
d = gdf["gdp_vs_median"]
print(f"GDP per head vs the median: {d.min():+.0f}% β¦ {d.max():+.0f}%; "
f"a plain RdBu puts its neutral colour at {(d.min() + d.max()) / 2:+.0f}%")
lim = d.abs().quantile(0.98)
print(f"symmetric range: Β±{lim:.0f}%")
for label, extra in (("quantiles", {}), ("quantiles, vmin/vmax = data range", {"vmin": v.min(), "vmax": v.max()})):
ax = gdf.plot(column="density", scheme="quantiles", k=5, cmap="OrRd", **extra)
print(f"{label:35} {len({tuple(c) for c in ax.collections[0].get_facecolors()})} distinct colours")
plt.close(ax.figure)
density: p95 2,176, max 4,829 β 95% of districts share 45% of a continuous ramp
GDP per head vs the median: -51% β¦ +338%; a plain RdBu puts its neutral colour at +143%
symmetric range: Β±161%
quantiles 5 distinct colours
quantiles, vmin/vmax = data range 1 distinct colours
Berlin and Munich stretch the density ramp to 4,829 people/kmΒ², so the 95% of districts below 2,176 share under half of it, and most of Germany comes out in its palest shades. GDP per head is worse for a diverging map: Wolfsburg sits 338% above the median and the poorest district 51% below, so a plain RdBu puts its neutral colour at +143%, and every district between the median and two and a half times it is coloured as if it were below average. A symmetric range β here the 98th percentile of the absolute deviation, Β±161% β puts the neutral colour back at zero. And passing the data's range as vmin/vmax to a classified plot, a natural thing to try, drew all five quantile classes in one colour: with a scheme set, those arguments apply to the class numbers 0 to 4, not to the values.
The fixes, in the order to reach for them:
# an outlier flattening a sequential ramp: classify, or clip and say so in the caption
gdf.plot(column="density", scheme="quantiles", k=5, cmap="OrRd", legend=True)
lo, hi = v.quantile([0.02, 0.98])
gdf.plot(column="density", cmap="OrRd", vmin=lo, vmax=hi, legend=True)
# a diverging value: a symmetric range puts the neutral colour at zero
gdf.plot(column="gdp_vs_median", cmap="RdBu", vmin=-lim, vmax=lim, legend=True)
# or keep both tails and pin zero, at the cost of unequal colour steps either side
from matplotlib.colors import TwoSlopeNorm
gdf.plot(column="gdp_vs_median", cmap="RdBu", norm=TwoSlopeNorm(vmin=d.min(), vcenter=0, vmax=d.max()))
Check the ramp's direction against the message too. OrRd, YlGnBu and viridis run light to dark as values rise, which reads as "more"; the _r suffix reverses any colormap. RdYlGn carries a judgement β green as good is right for income and wrong for pollution.
Save the choropleth map
To export the final map to an image:
from pathlib import Path
import matplotlib.pyplot as plt
Path("output").mkdir(parents=True, exist_ok=True)
fig, ax = plt.subplots(figsize=(10, 8))
gdf.plot(
column="density",
ax=ax,
cmap="OrRd",
legend=True,
edgecolor="black",
linewidth=0.2
)
ax.set_title("Population Density by Administrative Area")
ax.set_axis_off()
plt.savefig("output/population_density_map.png", dpi=300, bbox_inches="tight")
plt.close()
print(f"{Path('output/population_density_map.png').stat().st_size / 1e3:.0f} KB")
597 KB
Use dpi=300 for reports or print output. bbox_inches="tight" helps remove unnecessary margins.
German districts and regions as choropleths
The data used on this page
Germany's districts and regions from Eurostat (Β© EuroGeographics for the administrative boundaries; statistics Β© European Union): the NUTS 2021 boundaries at 1:20 million from GISCO, level 3 (400 districts and the "Extra-Regio" code) and level 2 (38 regions), joined to three Eurostat tables β population density for 2024 (demo_r_d3dens), GDP per inhabitant for 2023 (nama_10r_3gdp) and the 2024 unemployment rate for ages 15β74 (lfst_r_lfu3rt). The district layer is also written as a shapefile, the format the first examples read.
import io
from pathlib import Path
import geopandas as gpd
import pandas as pd
import requests
def eurostat(dataset, key, year):
r = requests.get(f"https://ec.europa.eu/eurostat/api/dissemination/sdmx/2.1/data/{dataset}/{key}"
f"?format=SDMX-CSV&startPeriod={year}&endPeriod={year}", timeout=300)
r.raise_for_status()
return pd.read_csv(io.StringIO(r.text))
def nuts(level):
g = gpd.read_file("https://gisco-services.ec.europa.eu/distribution/v2/nuts/geojson/"
f"NUTS_RG_20M_2021_4326_LEVL_{level}.geojson")
return g[g["CNTR_CODE"] == "DE"][["NUTS_ID", "NAME_LATN", "geometry"]]
Path("data").mkdir(exist_ok=True)
density = eurostat("demo_r_d3dens", "A.PER_KM2.", 2024).set_index("geo")["OBS_VALUE"]
gdp = eurostat("nama_10r_3gdp", "A.EUR_HAB.", 2023).set_index("geo")["OBS_VALUE"]
lfs = eurostat("lfst_r_lfu3rt", "all", 2024)
unemployment = lfs[(lfs["sex"] == "T") & (lfs["age"] == "Y15-74") & (lfs["isced11"] == "TOTAL")].set_index("geo")["OBS_VALUE"]
nuts3 = nuts(3).to_crs(3035)
nuts3["density"] = nuts3["NUTS_ID"].map(density)
nuts3["gdp_per_head"] = nuts3["NUTS_ID"].map(gdp)
nuts3.to_file("data/de_nuts3.gpkg")
nuts3.to_file("data/de_districts.shp")
nuts2 = nuts(2).to_crs(3035)
nuts2["unemployment_rate"] = nuts2["NUTS_ID"].map(unemployment)
nuts2.to_file("data/de_nuts2.gpkg")
print(len(nuts3), "districts,", nuts3["density"].notna().sum(), "with a density;",
len(nuts2), "regions,", nuts2["unemployment_rate"].notna().sum(), "with a rate")
401 districts, 394 with a density; 38 regions, 37 with a rate
Example 1: Basic choropleth from a shapefile
import geopandas as gpd
import matplotlib.pyplot as plt
gdf = gpd.read_file("data/de_districts.shp")
fig, ax = plt.subplots(figsize=(10, 8))
gdf.plot(
column="density",
ax=ax,
cmap="OrRd",
legend=True
)
ax.set_title("Population Density by District")
ax.set_axis_off()
plt.show()
print(list(gdf.columns)[:4], len(gdf))
['NUTS_ID', 'NAME_LATN', 'density', 'gdp_per_he'] 401
The shapefile has quietly renamed a column: gdp_per_head is eleven characters and the format allows ten, so it comes back as gdp_per_he. Code that plots column="gdp_per_head" from the shapefile fails with a KeyError; the GeoPackage keeps the name, which is why the next examples read that.
Example 2: Choropleth from GeoJSON with custom styling
import geopandas as gpd
import matplotlib.pyplot as plt
gdf = gpd.read_file("data/de_nuts3.gpkg")
fig, ax = plt.subplots(figsize=(11, 8))
gdf.plot(
column="gdp_per_head",
ax=ax,
cmap="YlGnBu",
legend=True,
edgecolor="white",
linewidth=0.5,
missing_kwds={"color": "lightgrey", "label": "No data"}
)
ax.set_title("GDP per Inhabitant by District, 2023 (EUR)", fontsize=14)
ax.set_axis_off()
plt.show()
print(gdf["gdp_per_head"].isna().sum(), "districts drawn as No data;",
gdf.loc[gdf["gdp_per_head"].idxmax(), "NAME_LATN"], "highest at", gdf["gdp_per_head"].max())
7 districts drawn as No data; Wolfsburg, Kreisfreie Stadt highest at 185100.0
Example 3: Choropleth with classified value ranges
This example requires mapclassify to be installed.
import geopandas as gpd
import matplotlib.pyplot as plt
gdf = gpd.read_file("data/de_nuts2.gpkg")
fig, ax = plt.subplots(figsize=(10, 8))
gdf.plot(
column="unemployment_rate",
ax=ax,
cmap="PuRd",
legend=True,
scheme="fisher_jenks",
k=5,
edgecolor="black",
linewidth=0.2
)
ax.set_title("Unemployment Rate by Region, 2024 (%)")
ax.set_axis_off()
plt.show()
import mapclassify
rates = gdf["unemployment_rate"].dropna()
import numpy as np
print("missing:", gdf.loc[gdf["unemployment_rate"].isna(), "NAME_LATN"].tolist())
print("fisher_jenks: ", [round(float(b), 1) for b in mapclassify.FisherJenks(rates, k=5).bins])
for seed in (1, 2, 3):
np.random.seed(seed)
print(f"natural_breaks (seed {seed}):", [round(float(b), 1) for b in mapclassify.NaturalBreaks(rates, k=5).bins])
missing: ['Trier']
fisher_jenks: [2.8, 3.3, 3.7, 4.3, 5.6]
natural_breaks (seed 1): [2.8, 3.3, 3.7, 4.3, 5.6]
natural_breaks (seed 2): [2.8, 3.3, 3.7, 4.3, 5.6]
natural_breaks (seed 3): [2.9, 3.4, 3.7, 4.3, 5.6]
natural_breaks is mapclassify's NaturalBreaks, a k-means classifier with random starting points, and the third seed moved two class boundaries. A map made twice from the same data should not change its legend, so this example uses fisher_jenks, which finds the optimal breaks deterministically.
Example 4: Export the final map image
from pathlib import Path
import geopandas as gpd
import matplotlib.pyplot as plt
Path("output").mkdir(parents=True, exist_ok=True)
gdf = gpd.read_file("data/de_nuts3.gpkg")
fig, ax = plt.subplots(figsize=(12, 9))
gdf.plot(
column="gdp_per_head",
ax=ax,
cmap="viridis",
legend=True,
edgecolor="black",
linewidth=0.3
)
ax.set_title("GDP per Inhabitant by District, 2023")
ax.set_axis_off()
plt.savefig("output/gdp_per_head.png", dpi=300, bbox_inches="tight")
plt.close()
print(sorted(p.name for p in Path("output").glob("*.png")))
['gdp_per_head.png', 'population_density_map.png']
Example 5: a check that names the cause
A function that inspects the column before the map is drawn catches most of the table above:
def diagnose_choropleth(gdf, column, *, scheme=None, k=5, cmap="OrRd"):
v = gdf[column]
if not pd.api.types.is_numeric_dtype(v):
return [f"'{column}' is {v.dtype}, not numeric β convert with pd.to_numeric(..., errors='coerce')"]
problems, vv = [], v.dropna()
if v.isna().any():
problems.append(f"{v.isna().sum()} of {len(gdf)} areas have no value β pass missing_kwds")
if vv.quantile(0.95) > 0 and vv.max() / vv.quantile(0.95) > 3:
problems.append(f"max is {vv.max() / vv.quantile(0.95):.1f}x the 95th percentile β classify or clip")
if scheme is None:
problems.append("no scheme β a continuous ramp on this column; try scheme='quantiles'")
else:
counts = [int(n) for n in mapclassify.classify(vv, scheme, k=k).counts]
if max(counts) / sum(counts) > 0.6:
problems.append(f"'{scheme}' puts {max(counts) / sum(counts):.0%} in one class {counts}")
if (vv < 0).any() and (vv > 0).any() and cmap.removesuffix("_r") not in {"RdBu", "PiYG", "BrBG", "coolwarm"}:
problems.append(f"values cross zero but '{cmap}' is sequential β use a diverging ramp, symmetric range")
return problems or ["no obvious problem β check the colormap direction by eye"]
gdf = gpd.read_file("data/de_nuts3.gpkg")
gdf["gdp_vs_median"] = (gdf["gdp_per_head"] / gdf["gdp_per_head"].median() - 1) * 100
text = gdf.assign(density=gdf["density"].map("{:.1f}".format))
for frame, column, scheme, cmap in ((gdf, "density", "equal_interval", "OrRd"), (gdf, "gdp_vs_median", None, "OrRd"),
(gdf, "density", "fisher_jenks", "OrRd"), (text, "density", "quantiles", "OrRd")):
print(f"{column}, scheme={scheme}{' (as text)' if frame is text else ''}:")
for problem in diagnose_choropleth(frame, column, scheme=scheme, cmap=cmap):
print(f" β {problem}")
density, scheme=equal_interval:
β 7 of 401 areas have no value β pass missing_kwds
β 'equal_interval' puts 80% in one class [315, 53, 19, 5, 2]
gdp_vs_median, scheme=None:
β 7 of 401 areas have no value β pass missing_kwds
β max is 3.5x the 95th percentile β classify or clip
β no scheme β a continuous ramp on this column; try scheme='quantiles'
β values cross zero but 'OrRd' is sequential β use a diverging ramp, symmetric range
density, scheme=fisher_jenks:
β 7 of 401 areas have no value β pass missing_kwds
β 'fisher_jenks' puts 65% in one class [256, 60, 52, 24, 2]
density, scheme=quantiles (as text):
β 'density' is str, not numeric β convert with pd.to_numeric(..., errors='coerce')
Every finding is a real property of these columns. Equal intervals put 80% of the districts in one class, and even Fisher-Jenks 65%, because density is right-skewed; GDP relative to the median crosses zero and has a long upper tail, so a sequential ramp with no scheme is wrong twice over; and the same densities written as text are caught before they reach plot, where a string column would be drawn as 394 unordered categories. The thresholds are chosen to be loud rather than precise: a false positive costs a moment's thought, and a false negative ships.
Three decisions between a table and a map
A choropleth makes three mappings, and each failed differently here. Area to value is a join, and a join is only as good as the two vintages agreeing: the 2024 density figures use Thuringia's redrawn district codes, the 2021 boundaries do not, and seven districts came through with no value. Value to class is the classification, and it is an analytical choice rather than a styling one: equal intervals put 315 of 394 districts in the lightest class and only Berlin and Munich in the darkest, quantiles force about 79 into each, and Fisher-Jenks follows the gaps in the data. Class to colour is the legend, and it should not depend on chance β which is why the classified example uses Fisher-Jenks rather than the randomly started natural_breaks.
Missing values behave like a fourth, colour-shaped bug: an area with no value is not drawn, and a reader takes the hole for a zero or a boundary error. A placeholder such as 0 or -999 standing in for "unknown" is worse, because it plots as a real class; one value far more common than any other is its tell.
The values themselves should be rates or densities. A district is coloured by its area on the page, so a raw total β people, not people per kmΒ² β mostly shows which districts are large.
Text columns, vintages and point layers
- A numeric column stored as text plots as categories; convert it with
pd.to_numeric(..., errors="coerce")first. - Missing values disappear by default.
missing_kwdsdraws them in a neutral colour with a legend entry; dropping them leaves an unexplained hole. - Check boundary and statistics vintages before joining: matching codes from different years is how Thuringia lost seven districts.
vmin/vmaxdo not combine withscheme. With a scheme set they apply to the class numbers, 0 to kβ1, so passing the data's own range drew all five density classes in one colour above. Classification and continuous normalisation are alternatives.str.rstrip("_r")is not a suffix strip. It removes characters, so it turns"Spectral"into"Spect";removesuffix("_r")is the method that means what it says.- Categorical data needs
categorical=Trueand a qualitative palette such astab10; a sequential ramp implies an order that is not there. - Colour-blind readers cannot separate red from green.
viridis,cividisand ColorBrewer's safe ramps can. legend_kwds={"fmt": "{:,.0f}"}removes4828.60000from a classified legend.- Points are not areas. For point data use proportional symbols or a density surface, not a choropleth.
Internal links
For what each classification scheme assumes, read choropleth classification explained.
For related GeoPandas tasks, see How to Read a Shapefile in Python with GeoPandas and How to Reproject Spatial Data in Python (GeoPandas).
If you need to prepare output data for other tools, see How to Read and Write GeoJSON in Python with GeoPandas.
If your layer draws in the wrong place or looks distorted, check Why GeoPandas Plot Is Not Showing the Correct Map.
FAQ
How do I create a choropleth map in GeoPandas?
Load a polygon dataset with gpd.read_file(), then call gdf.plot(column="your_field", legend=True). Add cmap, edgecolor, and figsize for better output.
Does GeoPandas work with shapefiles and GeoJSON for choropleth maps?
Yes. GeoPandas supports both shapefiles and GeoJSON through read_file(), so you can use the same choropleth workflow with either format.
What column type should I use for a choropleth map?
Use a numeric column such as integer or float. If your values are strings, convert them to numeric before plotting.
How do I handle missing values in a GeoPandas choropleth?
Use missing_kwds to style polygons with null values, or remove null rows with gdf[gdf["field"].notna()].
How do I join attribute values from a CSV before making a choropleth?
Read the CSV with pandas and merge() it onto the polygon GeoDataFrame using a shared key column, keeping the GeoDataFrame on the left so the geometry is preserved: gdf = gdf.merge(df, on="region_id", how="left"). Then plot the merged numeric column as usual.
How do I add a north arrow, scale bar, or basemap to a GeoPandas choropleth?
GeoPandas does not draw those itself; use the contextily package for a basemap and matplotlib for annotations. Reproject your layer to EPSG:3857 first with gdf.to_crs(epsg=3857), then call contextily.add_basemap(ax) after plotting.
How do I control the color classification breakpoints manually?
Pass an explicit list to classification_kwds with the user_defined scheme: gdf.plot(column="density", scheme="user_defined", classification_kwds={"bins": [10, 50, 100, 500]}). This requires mapclassify and gives you fixed, reproducible class edges instead of data-driven ones.
How do I move or resize the choropleth legend?
The continuous color bar is controlled with legend_kwds, for example legend_kwds={"shrink": 0.5, "label": "Density"}. For classified maps the legend is a standard matplotlib legend, so you can reposition it afterward with ax.get_legend().set_bbox_to_anchor((1, 0.5)).
Why is my whole map one colour?
Either no scheme was passed and an outlier is flattening the continuous ramp β Berlin and Munich left the other 95% of districts under half of it β or equal_interval on skewed data has put nearly everything in the first class. Check the class counts before changing the colours.
Why is the neutral colour of my diverging map not at zero?
Matplotlib centres the ramp on the midpoint of the data's range, not on zero. Pass a symmetric vmin=-lim, vmax=lim, or norm=TwoSlopeNorm(vcenter=0, ...) when the tails differ.
vmin and vmax are doing something strange with a scheme.
With scheme= set they apply to the class numbers, not to your values, so the data's own range squeezes every class into one colour. Use one or the other.