Add a Basemap to a Map in Python with contextily

Put street, topographic or satellite map tiles behind GeoPandas and Matplotlib plots with contextily: ctx.add_basemap(), coordinate systems, zoom levels, providers, polygons over a basemap and saving tiles for offline use.

To add a basemap to a map in Python, plot your points or polygons with GeoPandas, then call ctx.add_basemap(ax, crs=gdf.crs, source=...) from contextily. It downloads the web map tiles that cover the axes' extent, stitches them into one image and draws it behind your data. Without it, a scatter of latitude and longitude is a cloud of dots with nothing to tell the reader where they are.

This post uses contextily 1.7.1 and GeoPandas 1.2 with Matplotlib 3.11. Install them with pip install contextily geopandas matplotlib. The tiles come from the US Geological Survey's The National Map, which is public domain and needs no API key, so the examples cover the United States. Other regions need a different tile provider (see the providers section).

Quick Example

The data is 700 simulated bike-share trip starts around downtown Denver, clustered around six busy spots (seeded, so you get the same map). The part to keep is the last four lines.

import contextily as ctx
import geopandas as gpd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(14)
hubs = pd.DataFrame({
    "hub": ["Union Station", "Civic Center", "Capitol Hill", "Cherry Creek", "RiNo", "Highlands"],
    "lat": [39.7527, 39.7366, 39.7312, 39.7180, 39.7690, 39.7600],
    "lon": [-105.0000, -104.9887, -104.9700, -104.9530, -104.9810, -105.0110],
    "weight": [0.26, 0.20, 0.16, 0.14, 0.14, 0.10],
})
which = rng.choice(len(hubs), size=700, p=hubs["weight"])
trips = pd.DataFrame({
    "lat": hubs["lat"].to_numpy()[which] + rng.normal(0, 0.0045, 700),
    "lon": hubs["lon"].to_numpy()[which] + rng.normal(0, 0.0060, 700),
})
trips = gpd.GeoDataFrame(trips, geometry=gpd.points_from_xy(trips["lon"], trips["lat"]), crs="EPSG:4326")

ax = trips.plot(figsize=(8, 8), markersize=16, color="#d1495b", alpha=0.65, edgecolor="white", linewidth=0.4)
ctx.add_basemap(ax, crs=trips.crs, source=ctx.providers.USGS.USTopo)
ax.set_axis_off()
plt.show()

Topographic map of downtown Denver with 700 red semi-transparent points clustered around Union Station, Civic Center, Capitol Hill, Cherry Creek, RiNo and the Highlands

crs=trips.crs tells contextily which coordinate system the axes are in, and it reprojects the tiles to match. The source is a tile provider; ctx.providers.USGS.USTopo is a topographic style with the attribution text already built in, which contextily draws in the bottom corner. Keep that credit on any published map.

Plot your data first, then add the basemap. add_basemap() reads the axes' limits to decide which tiles to fetch, so the order matters. The first call downloads tiles, and contextily caches them on disk, so rerunning the script is fast.

Which coordinate system does contextily need?

Web map tiles use Web Mercator (EPSG:3857), where coordinates are in meters from the equator and the prime meridian. You have two ways to match them. Pass crs= and let contextily warp the tiles to your data (as above), or convert your data to EPSG:3857 and skip crs=:

trips_3857 = trips.to_crs(epsg=3857)
print(trips_3857.crs.to_string(), trips_3857.total_bounds.round(0))

ax = trips_3857.plot(figsize=(6, 6), markersize=10, color="#d1495b", alpha=0.6)
ctx.add_basemap(ax, source=ctx.providers.USGS.USTopo)  # no crs needed: the axes are already Web Mercator
ax.set_axis_off()
plt.show()
EPSG:3857 [-11691816.   4823365. -11681912.   4833712.]

Converting first is the better habit when you add other layers, since polygons and labels then share one coordinate system. Passing crs= is a good shortcut for a quick plot, since contextily resamples the tiles to fit. If your axes are in latitude and longitude and you forget crs=, contextily treats the numbers as Web Mercator meters. It then infers a zoom level of 30, which no provider has, and the download fails with a 404 error.

How do I change the zoom level of a contextily basemap?

zoom="auto" is the default, and it picks a level from the axes' size. Pass zoom= with an integer to force one. Each step up doubles the detail and roughly quadruples the number of tiles to download:

fig, axes = plt.subplots(1, 3, figsize=(13, 4.6))
for ax, zoom in zip(axes, [10, 12, 14]):
    trips_3857.plot(ax=ax, markersize=6, color="#d1495b", alpha=0.6)
    ctx.add_basemap(ax, source=ctx.providers.USGS.USTopo, zoom=zoom, attribution=False)
    ax.set_title(f"zoom={zoom}")
    ax.set_axis_off()
fig.tight_layout()
plt.show()

Three panels of the same Denver map at zoom 10, 12 and 14, showing the basemap going from blurry to street-level detail

Zoom 10 is blurry at this size because each tile covers a large area and is stretched. Zoom 14 is crisp but needs many more tiles, which is slower and heavier on the provider's server. For a map the width of a city, zoom_adjust=1 (one level above the automatic choice) is often the right fix when "auto" looks soft. The attribution=False here is only to keep the three small panels clean. Add the credit back to anything you publish.

How do I use a different map style or provider?

ctx.providers is a nested collection of tile sources. Print list(ctx.providers.USGS) to see the options for a provider, or use ctx.providers.USGS.USImagery for satellite imagery:

print(list(ctx.providers.USGS))

fig, ax = plt.subplots(figsize=(7, 7))
trips_3857.plot(ax=ax, markersize=14, color="#ffd166", edgecolor="black", linewidth=0.4, alpha=0.9)
ctx.add_basemap(ax, source=ctx.providers.USGS.USImagery)
ax.set_axis_off()
plt.show()
['USTopo', 'USImagery', 'USImageryTopo']

Satellite imagery of downtown Denver with yellow dots for bike-share trip starts

Light colors on a dark imagery basemap, and dark or saturated colors on a pale topographic one, keep the points readable. Providers differ in coverage, terms and rate limits, so check them before you pick one. Two things I ran into:

  • OpenStreetMap's own tile servers returned a 403 "Access blocked" error for contextily's default requests, because their usage policy requires an identifying User-Agent. add_basemap() takes a headers= dictionary for that, but read the policy first. Tiles from heavy or anonymous automated use get blocked.
  • USGS.USImageryTopo returned 404 errors for the area in this post when I ran it, so it is not used here.

Outside the US, look at the providers listed in the contextily docs that fit your terms, and use a provider's API key if it asks for one (source accepts a provider object with the key filled in).

How do I draw polygons and labels over the basemap?

Anything in a GeoDataFrame in the same coordinate system can sit on the tiles. Here each hub gets a 700-meter circle and a label. Buffer in a local projected CRS (a UTM zone, EPSG:32613 for Denver) and then convert to Web Mercator. Buffering directly in EPSG:3857 would be wrong, because Web Mercator stretches distances by about 30% at Denver's latitude:

import matplotlib.patheffects as pe

hub_points = gpd.GeoDataFrame(hubs, geometry=gpd.points_from_xy(hubs["lon"], hubs["lat"]), crs="EPSG:4326")
circles = hub_points.to_crs(epsg=32613).buffer(700).to_crs(epsg=3857)

fig, ax = plt.subplots(figsize=(8, 8))
circles.plot(ax=ax, facecolor="#2a9d8f", edgecolor="#1b6b61", alpha=0.35, linewidth=2)
trips_3857.plot(ax=ax, markersize=5, color="#264653", alpha=0.5)
for name, point in zip(hub_points["hub"], hub_points.to_crs(epsg=3857).geometry):
    ax.annotate(name, (point.x, point.y), ha="center", fontsize=10, fontweight="bold",
                path_effects=[pe.withStroke(linewidth=3, foreground="white")])
ctx.add_basemap(ax, source=ctx.providers.USGS.USTopo, zoom=13)
ax.set_axis_off()
plt.show()

inside = trips_3857.within(circles.union_all())
print(f"{inside.mean():.0%} of trip starts are within 700 m of a hub")

Denver topographic map with six teal circles around the hubs, small dark trip points and bold white-outlined hub names

66% of trip starts are within 700 m of a hub

The white path_effects outline keeps text readable on a busy basemap. Set alpha on polygons so the map shows through. Call add_basemap() after plotting your layers: it draws the tiles underneath them.

How do I save the basemap for offline use?

ctx.bounds2raster() downloads the tiles for a bounding box and writes them to one GeoTIFF. Pass that file as the source and add_basemap() reads it from disk, with no network. This is also how you make a basemap you can reuse in a script that runs often:

west, south, east, north = trips.total_bounds
_ = ctx.bounds2raster(west, south, east, north, "denver.tif", ll=True, zoom=12, source=ctx.providers.USGS.USTopo)

ax = trips_3857.plot(figsize=(6, 6), markersize=8, color="#d1495b", alpha=0.6)
ctx.add_basemap(ax, source="denver.tif")  # reads the local file
ax.set_axis_off()
plt.show()

ll=True says the bounds are in latitude and longitude, and the raster is saved in Web Mercator. The raster only covers the box you asked for, so zooming out beyond it leaves blank space. The tile provider's attribution is not stored in the file, so add the credit text yourself, for example with ax.text(), when you publish a map made from one.

contextily vs Folium vs Plotly maps

contextily Folium Plotly maps
Output Static image (Matplotlib) Interactive web map Interactive web map
Works with Matplotlib, GeoPandas Leaflet px.scatter_map, px.choropleth_map
Pan and zoom No Yes Yes
Best for Reports, slides, papers, print Exploring on screen Dashboards and embedded charts
Needs the network when drawing Yes (unless you use a saved raster) In the viewer's browser In the viewer's browser

Use contextily when the output is an image, because you control every Matplotlib detail: colors, annotations, subplots and export size. Use Folium or Plotly when the reader should pan and zoom.

Practical Tips

  • Plot first, then add_basemap(). It needs the axes limits to decide which tiles to download.
  • Mind the CRS. Pass crs=gdf.crs, or convert to EPSG:3857 first. A map with the wrong CRS shows the wrong place.
  • Compute distances and areas in a local projected CRS, such as a UTM zone, not in Web Mercator or latitude and longitude.
  • Keep the attribution. add_basemap() draws it by default. Each provider's terms require credit, so don't remove it from a published map.
  • Don't hammer a tile server. A high zoom over a large area downloads thousands of tiles. Contextily caches them, and bounds2raster() lets you fetch once.
  • A basemap is a background, not data. Light, desaturated styles keep attention on your layer. A pale topographic style or a muted gray works better than satellite imagery for most analysis maps.

Similar Topics