Note
Adding a background map to plots#
This example shows how you can add a background basemap to plots created with the geopandas .plot()
method. This makes use of the contextily package to retrieve web map tiles from several sources (OpenStreetMap, CartoDB). Also have a look at contextily’s introduction guide for possible new features not covered here.
[1]:
import geopandas
import geodatasets
import contextily as cx
Let’s use the NYC borough boundary data that is available in geopandas datasets. Plotting this gives the following result:
[2]:
df = geopandas.read_file(geodatasets.get_path("nybb"))
ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor="k")
Matching coordinate systems#
Before adding web map tiles to this plot, we first need to ensure the coordinate reference systems (CRS) of the tiles and the data match. Web map tiles are typically provided in Web Mercator (EPSG 3857), so let us first check what CRS our NYC boroughs are in:
[3]:
df.crs
[3]:
<Projected CRS: EPSG:2263>
Name: NAD83 / New York Long Island (ftUS)
Axis Info [cartesian]:
- X[east]: Easting (US survey foot)
- Y[north]: Northing (US survey foot)
Area of Use:
- name: United States (USA) - New York - counties of Bronx; Kings; Nassau; New York; Queens; Richmond; Suffolk.
- bounds: (-74.26, 40.47, -71.8, 41.3)
Coordinate Operation:
- name: SPCS83 New York Long Island zone (US survey foot)
- method: Lambert Conic Conformal (2SP)
Datum: North American Datum 1983
- Ellipsoid: GRS 1980
- Prime Meridian: Greenwich
Now we know the CRS do not match, so we need to choose in which CRS we wish to visualize the data: either the CRS of the tiles, the one of the data, or even a different one.
The first option to match CRS is to leverage the to_crs
method of GeoDataFrames to convert the CRS of our data, here to Web Mercator:
[4]:
df_wm = df.to_crs(epsg=3857)
We can then use add_basemap
function of contextily to easily add a background map to our plot:
[5]:
ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor="k")
cx.add_basemap(ax)
If we want to convert the CRS of the tiles instead, which might be advisable for large datasets, we can use the crs
keyword argument of add_basemap
as follows:
[6]:
ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor="k")
cx.add_basemap(ax, crs=df.crs)
This reprojects map tiles to a target CRS which may in some cases cause a loss of sharpness. See contextily’s guide on warping tiles for more information on the subject.
Controlling the level of detail#
We can control the detail of the map tiles using the optional zoom
keyword (be careful to not specify a too high zoom
level, as this can result in a large download).:
[7]:
ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor="k")
cx.add_basemap(ax, zoom=12)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[7], line 2
1 ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor="k")
----> 2 cx.add_basemap(ax, zoom=12)
File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/latest/lib/python3.12/site-packages/contextily/plotting.py:134, in add_basemap(ax, zoom, source, interpolation, attribution, attribution_size, reset_extent, crs, resampling, zoom_adjust, **extra_imshow_args)
130 left, right, bottom, top = _reproj_bb(
131 left, right, bottom, top, crs, "epsg:3857"
132 )
133 # Download image
--> 134 image, extent = bounds2img(
135 left, bottom, right, top, zoom=zoom, source=source, ll=False, zoom_adjust=zoom_adjust
136 )
137 # Warping
138 if crs is not None:
File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/latest/lib/python3.12/site-packages/contextily/tile.py:265, in bounds2img(w, s, e, n, zoom, source, ll, wait, max_retries, n_connections, use_cache, zoom_adjust)
262 arrays = Parallel(n_jobs=n_connections, prefer=preferred_backend)(
263 delayed(fetch_tile_fn)(tile_url, wait, max_retries) for tile_url in tile_urls)
264 # merge downloaded tiles
--> 265 merged, extent = _merge_tiles(tiles, arrays)
266 # lon/lat extent --> Spheric Mercator
267 west, south, east, north = extent
File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/latest/lib/python3.12/site-packages/contextily/tile.py:670, in _merge_tiles(tiles, arrays)
668 for ind, arr in zip(indices, arrays):
669 x, y = ind
--> 670 img[y * h : (y + 1) * h, x * w : (x + 1) * w, :] = arr
672 bounds = np.array([mt.bounds(t) for t in tiles])
673 west, south, east, north = (
674 min(bounds[:, 0]),
675 min(bounds[:, 1]),
676 max(bounds[:, 2]),
677 max(bounds[:, 3]),
678 )
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
Choosing a different style#
By default, contextily uses the OpenStreetMap HOT style. We can specify a different style using cx.providers
:
[8]:
ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor="k")
cx.add_basemap(ax, source=cx.providers.CartoDB.Positron)
ax.set_axis_off()
Adding labels as an overlay#
Sometimes, when you plot data on a basemap, the data will obscure some important map elements, such as labels, that you would otherwise want to see unobscured. Some map tile providers offer multiple sets of partially transparent tiles to solve this, and contextily
will do its best to auto-detect these transparent layers and put them on top.
[9]:
ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor="k")
cx.add_basemap(ax, source=cx.providers.CartoDB.PositronNoLabels)
cx.add_basemap(ax, source=cx.providers.CartoDB.PositronOnlyLabels)
By splitting the layers like this, you can also independently manipulate the level of zoom on each layer, for example to make labels larger while still showing a lot of detail.
[10]:
ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor="k")
cx.add_basemap(ax, source=cx.providers.CartoDB.PositronNoLabels, zoom=12)
cx.add_basemap(ax, source=cx.providers.CartoDB.PositronOnlyLabels, zoom=10)