Note

This page was generated from gallery/plotting_basemap_background.ipynb.
Interactive online version: Binder badge

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")
../_images/gallery_plotting_basemap_background_3_0.png

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)
---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:470, in _retryer(tile_url, wait, max_retries, headers)
    469 request = requests.get(tile_url, headers={"user-agent": USER_AGENT, **headers})
--> 470 request.raise_for_status()
    471 with io.BytesIO(request.content) as image_stream:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/requests/models.py:1167, in Response.raise_for_status(self)
   1166 if http_error_msg:
-> 1167     raise HTTPError(http_error_msg, response=self)

HTTPError: 502 Server Error: Bad Gateway for url: https://a.tile.openstreetmap.fr/hot/11/601/768.png

During handling of the above exception, another exception occurred:

HTTPError                                 Traceback (most recent call last)
File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:470, in _retryer(tile_url, wait, max_retries, headers)
    469 request = requests.get(tile_url, headers={"user-agent": USER_AGENT, **headers})
--> 470 request.raise_for_status()
    471 with io.BytesIO(request.content) as image_stream:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/requests/models.py:1167, in Response.raise_for_status(self)
   1166 if http_error_msg:
-> 1167     raise HTTPError(http_error_msg, response=self)

HTTPError: 502 Server Error: Bad Gateway for url: https://a.tile.openstreetmap.fr/hot/11/601/768.png

During handling of the above exception, another exception occurred:

HTTPError                                 Traceback (most recent call last)
File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:470, in _retryer(tile_url, wait, max_retries, headers)
    469 request = requests.get(tile_url, headers={"user-agent": USER_AGENT, **headers})
--> 470 request.raise_for_status()
    471 with io.BytesIO(request.content) as image_stream:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/requests/models.py:1167, in Response.raise_for_status(self)
   1166 if http_error_msg:
-> 1167     raise HTTPError(http_error_msg, response=self)

HTTPError: 502 Server Error: Bad Gateway for url: https://a.tile.openstreetmap.fr/hot/11/601/768.png

During handling of the above exception, another exception occurred:

HTTPError                                 Traceback (most recent call last)
Cell In[5], line 2
      1 ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor="k")
----> 2 cx.add_basemap(ax)

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/plotting.py:138, in add_basemap(ax, zoom, source, headers, interpolation, attribution, attribution_size, reset_extent, crs, resampling, zoom_adjust, **extra_imshow_args)
    134     left, right, bottom, top = _reproj_bb(
    135         left, right, bottom, top, crs, "epsg:3857"
    136     )
    137 # Download image
--> 138 image, extent = bounds2img(
    139     left,
    140     bottom,
    141     right,
    142     top,
    143     zoom=zoom,
    144     source=source,
    145     headers=headers,
    146     ll=False,
    147     zoom_adjust=zoom_adjust,
    148 )
    149 # Warping
    150 if crs is not None:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:298, in bounds2img(w, s, e, n, zoom, source, headers, ll, wait, max_retries, n_connections, use_cache, zoom_adjust)
    294 preferred_backend = (
    295     "threads" if (n_connections == 1 or not use_cache) else "processes"
    296 )
    297 fetch_tile_fn = memory.cache(_fetch_tile) if use_cache else _fetch_tile
--> 298 arrays = Parallel(n_jobs=n_connections, prefer=preferred_backend)(
    299     delayed(fetch_tile_fn)(tile_url, wait, max_retries, headers) for tile_url in tile_urls
    300 )
    301 # merge downloaded tiles
    302 merged, extent = _merge_tiles(tiles, arrays)

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/parallel.py:1986, in Parallel.__call__(self, iterable)
   1984     output = self._get_sequential_output(iterable)
   1985     next(output)
-> 1986     return output if self.return_generator else list(output)
   1988 # Let's create an ID that uniquely identifies the current call. If the
   1989 # call is interrupted early and that the same instance is immediately
   1990 # reused, this id will be used to prevent workers that were
   1991 # concurrently finalizing a task from the previous call to run the
   1992 # callback.
   1993 with self._lock:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/parallel.py:1914, in Parallel._get_sequential_output(self, iterable)
   1912 self.n_dispatched_batches += 1
   1913 self.n_dispatched_tasks += 1
-> 1914 res = func(*args, **kwargs)
   1915 self.n_completed_tasks += 1
   1916 self.print_progress()

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/memory.py:607, in MemorizedFunc.__call__(self, *args, **kwargs)
    605 def __call__(self, *args, **kwargs):
    606     # Return the output, without the metadata
--> 607     return self._cached_call(args, kwargs, shelving=False)[0]

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/memory.py:562, in MemorizedFunc._cached_call(self, args, kwargs, shelving)
    556     self.warn(
    557         f"Computing func {func_name}, argument hash {args_id} "
    558         f"in location {location}"
    559     )
    561 # Returns the output but not the metadata
--> 562 return self._call(call_id, args, kwargs, shelving)

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/memory.py:832, in MemorizedFunc._call(self, call_id, args, kwargs, shelving)
    830 self._before_call(args, kwargs)
    831 start_time = time.time()
--> 832 output = self.func(*args, **kwargs)
    833 return self._after_call(call_id, args, kwargs, shelving, output, start_time)

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:328, in _fetch_tile(tile_url, wait, max_retries, headers)
    327 def _fetch_tile(tile_url, wait, max_retries, headers: dict[str, str]):
--> 328     array = _retryer(tile_url, wait, max_retries, headers)
    329     return array

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:488, in _retryer(tile_url, wait, max_retries, headers)
    486     time.sleep(wait)
    487     max_retries -= 1
--> 488     request = _retryer(tile_url, wait, max_retries, headers)
    489 else:
    490     raise requests.HTTPError("Connection reset by peer too many times. "
    491                              f"Last message was: {request.status_code} "
    492                              f"Error: {request.reason} for url: {request.url}")

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:488, in _retryer(tile_url, wait, max_retries, headers)
    486     time.sleep(wait)
    487     max_retries -= 1
--> 488     request = _retryer(tile_url, wait, max_retries, headers)
    489 else:
    490     raise requests.HTTPError("Connection reset by peer too many times. "
    491                              f"Last message was: {request.status_code} "
    492                              f"Error: {request.reason} for url: {request.url}")

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:490, in _retryer(tile_url, wait, max_retries, headers)
    488     request = _retryer(tile_url, wait, max_retries, headers)
    489 else:
--> 490     raise requests.HTTPError("Connection reset by peer too many times. "
    491                              f"Last message was: {request.status_code} "
    492                              f"Error: {request.reason} for url: {request.url}")

HTTPError: Connection reset by peer too many times. Last message was: 502 Error: Bad Gateway for url: https://a.tile.openstreetmap.fr/hot/11/601/768.png
../_images/gallery_plotting_basemap_background_9_1.png

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)
---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:470, in _retryer(tile_url, wait, max_retries, headers)
    469 request = requests.get(tile_url, headers={"user-agent": USER_AGENT, **headers})
--> 470 request.raise_for_status()
    471 with io.BytesIO(request.content) as image_stream:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/requests/models.py:1167, in Response.raise_for_status(self)
   1166 if http_error_msg:
-> 1167     raise HTTPError(http_error_msg, response=self)

HTTPError: 502 Server Error: Bad Gateway for url: https://a.tile.openstreetmap.fr/hot/11/601/768.png

During handling of the above exception, another exception occurred:

HTTPError                                 Traceback (most recent call last)
File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:470, in _retryer(tile_url, wait, max_retries, headers)
    469 request = requests.get(tile_url, headers={"user-agent": USER_AGENT, **headers})
--> 470 request.raise_for_status()
    471 with io.BytesIO(request.content) as image_stream:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/requests/models.py:1167, in Response.raise_for_status(self)
   1166 if http_error_msg:
-> 1167     raise HTTPError(http_error_msg, response=self)

HTTPError: 502 Server Error: Bad Gateway for url: https://a.tile.openstreetmap.fr/hot/11/601/768.png

During handling of the above exception, another exception occurred:

HTTPError                                 Traceback (most recent call last)
File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:470, in _retryer(tile_url, wait, max_retries, headers)
    469 request = requests.get(tile_url, headers={"user-agent": USER_AGENT, **headers})
--> 470 request.raise_for_status()
    471 with io.BytesIO(request.content) as image_stream:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/requests/models.py:1167, in Response.raise_for_status(self)
   1166 if http_error_msg:
-> 1167     raise HTTPError(http_error_msg, response=self)

HTTPError: 502 Server Error: Bad Gateway for url: https://a.tile.openstreetmap.fr/hot/11/601/768.png

During handling of the above exception, another exception occurred:

HTTPError                                 Traceback (most recent call last)
Cell In[6], line 2
      1 ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor="k")
----> 2 cx.add_basemap(ax, crs=df.crs)

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/plotting.py:138, in add_basemap(ax, zoom, source, headers, interpolation, attribution, attribution_size, reset_extent, crs, resampling, zoom_adjust, **extra_imshow_args)
    134     left, right, bottom, top = _reproj_bb(
    135         left, right, bottom, top, crs, "epsg:3857"
    136     )
    137 # Download image
--> 138 image, extent = bounds2img(
    139     left,
    140     bottom,
    141     right,
    142     top,
    143     zoom=zoom,
    144     source=source,
    145     headers=headers,
    146     ll=False,
    147     zoom_adjust=zoom_adjust,
    148 )
    149 # Warping
    150 if crs is not None:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:298, in bounds2img(w, s, e, n, zoom, source, headers, ll, wait, max_retries, n_connections, use_cache, zoom_adjust)
    294 preferred_backend = (
    295     "threads" if (n_connections == 1 or not use_cache) else "processes"
    296 )
    297 fetch_tile_fn = memory.cache(_fetch_tile) if use_cache else _fetch_tile
--> 298 arrays = Parallel(n_jobs=n_connections, prefer=preferred_backend)(
    299     delayed(fetch_tile_fn)(tile_url, wait, max_retries, headers) for tile_url in tile_urls
    300 )
    301 # merge downloaded tiles
    302 merged, extent = _merge_tiles(tiles, arrays)

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/parallel.py:1986, in Parallel.__call__(self, iterable)
   1984     output = self._get_sequential_output(iterable)
   1985     next(output)
-> 1986     return output if self.return_generator else list(output)
   1988 # Let's create an ID that uniquely identifies the current call. If the
   1989 # call is interrupted early and that the same instance is immediately
   1990 # reused, this id will be used to prevent workers that were
   1991 # concurrently finalizing a task from the previous call to run the
   1992 # callback.
   1993 with self._lock:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/parallel.py:1914, in Parallel._get_sequential_output(self, iterable)
   1912 self.n_dispatched_batches += 1
   1913 self.n_dispatched_tasks += 1
-> 1914 res = func(*args, **kwargs)
   1915 self.n_completed_tasks += 1
   1916 self.print_progress()

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/memory.py:607, in MemorizedFunc.__call__(self, *args, **kwargs)
    605 def __call__(self, *args, **kwargs):
    606     # Return the output, without the metadata
--> 607     return self._cached_call(args, kwargs, shelving=False)[0]

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/memory.py:562, in MemorizedFunc._cached_call(self, args, kwargs, shelving)
    556     self.warn(
    557         f"Computing func {func_name}, argument hash {args_id} "
    558         f"in location {location}"
    559     )
    561 # Returns the output but not the metadata
--> 562 return self._call(call_id, args, kwargs, shelving)

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/memory.py:832, in MemorizedFunc._call(self, call_id, args, kwargs, shelving)
    830 self._before_call(args, kwargs)
    831 start_time = time.time()
--> 832 output = self.func(*args, **kwargs)
    833 return self._after_call(call_id, args, kwargs, shelving, output, start_time)

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:328, in _fetch_tile(tile_url, wait, max_retries, headers)
    327 def _fetch_tile(tile_url, wait, max_retries, headers: dict[str, str]):
--> 328     array = _retryer(tile_url, wait, max_retries, headers)
    329     return array

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:488, in _retryer(tile_url, wait, max_retries, headers)
    486     time.sleep(wait)
    487     max_retries -= 1
--> 488     request = _retryer(tile_url, wait, max_retries, headers)
    489 else:
    490     raise requests.HTTPError("Connection reset by peer too many times. "
    491                              f"Last message was: {request.status_code} "
    492                              f"Error: {request.reason} for url: {request.url}")

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:488, in _retryer(tile_url, wait, max_retries, headers)
    486     time.sleep(wait)
    487     max_retries -= 1
--> 488     request = _retryer(tile_url, wait, max_retries, headers)
    489 else:
    490     raise requests.HTTPError("Connection reset by peer too many times. "
    491                              f"Last message was: {request.status_code} "
    492                              f"Error: {request.reason} for url: {request.url}")

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:490, in _retryer(tile_url, wait, max_retries, headers)
    488     request = _retryer(tile_url, wait, max_retries, headers)
    489 else:
--> 490     raise requests.HTTPError("Connection reset by peer too many times. "
    491                              f"Last message was: {request.status_code} "
    492                              f"Error: {request.reason} for url: {request.url}")

HTTPError: Connection reset by peer too many times. Last message was: 502 Error: Bad Gateway for url: https://a.tile.openstreetmap.fr/hot/11/601/768.png
../_images/gallery_plotting_basemap_background_11_1.png

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)
---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:470, in _retryer(tile_url, wait, max_retries, headers)
    469 request = requests.get(tile_url, headers={"user-agent": USER_AGENT, **headers})
--> 470 request.raise_for_status()
    471 with io.BytesIO(request.content) as image_stream:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/requests/models.py:1167, in Response.raise_for_status(self)
   1166 if http_error_msg:
-> 1167     raise HTTPError(http_error_msg, response=self)

HTTPError: 502 Server Error: Bad Gateway for url: https://a.tile.openstreetmap.fr/hot/12/1202/1536.png

During handling of the above exception, another exception occurred:

HTTPError                                 Traceback (most recent call last)
File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:470, in _retryer(tile_url, wait, max_retries, headers)
    469 request = requests.get(tile_url, headers={"user-agent": USER_AGENT, **headers})
--> 470 request.raise_for_status()
    471 with io.BytesIO(request.content) as image_stream:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/requests/models.py:1167, in Response.raise_for_status(self)
   1166 if http_error_msg:
-> 1167     raise HTTPError(http_error_msg, response=self)

HTTPError: 502 Server Error: Bad Gateway for url: https://a.tile.openstreetmap.fr/hot/12/1202/1536.png

During handling of the above exception, another exception occurred:

HTTPError                                 Traceback (most recent call last)
File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:470, in _retryer(tile_url, wait, max_retries, headers)
    469 request = requests.get(tile_url, headers={"user-agent": USER_AGENT, **headers})
--> 470 request.raise_for_status()
    471 with io.BytesIO(request.content) as image_stream:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/requests/models.py:1167, in Response.raise_for_status(self)
   1166 if http_error_msg:
-> 1167     raise HTTPError(http_error_msg, response=self)

HTTPError: 502 Server Error: Bad Gateway for url: https://a.tile.openstreetmap.fr/hot/12/1202/1536.png

During handling of the above exception, another exception occurred:

HTTPError                                 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/v1.1.4/lib/python3.13/site-packages/contextily/plotting.py:138, in add_basemap(ax, zoom, source, headers, interpolation, attribution, attribution_size, reset_extent, crs, resampling, zoom_adjust, **extra_imshow_args)
    134     left, right, bottom, top = _reproj_bb(
    135         left, right, bottom, top, crs, "epsg:3857"
    136     )
    137 # Download image
--> 138 image, extent = bounds2img(
    139     left,
    140     bottom,
    141     right,
    142     top,
    143     zoom=zoom,
    144     source=source,
    145     headers=headers,
    146     ll=False,
    147     zoom_adjust=zoom_adjust,
    148 )
    149 # Warping
    150 if crs is not None:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:298, in bounds2img(w, s, e, n, zoom, source, headers, ll, wait, max_retries, n_connections, use_cache, zoom_adjust)
    294 preferred_backend = (
    295     "threads" if (n_connections == 1 or not use_cache) else "processes"
    296 )
    297 fetch_tile_fn = memory.cache(_fetch_tile) if use_cache else _fetch_tile
--> 298 arrays = Parallel(n_jobs=n_connections, prefer=preferred_backend)(
    299     delayed(fetch_tile_fn)(tile_url, wait, max_retries, headers) for tile_url in tile_urls
    300 )
    301 # merge downloaded tiles
    302 merged, extent = _merge_tiles(tiles, arrays)

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/parallel.py:1986, in Parallel.__call__(self, iterable)
   1984     output = self._get_sequential_output(iterable)
   1985     next(output)
-> 1986     return output if self.return_generator else list(output)
   1988 # Let's create an ID that uniquely identifies the current call. If the
   1989 # call is interrupted early and that the same instance is immediately
   1990 # reused, this id will be used to prevent workers that were
   1991 # concurrently finalizing a task from the previous call to run the
   1992 # callback.
   1993 with self._lock:

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/parallel.py:1914, in Parallel._get_sequential_output(self, iterable)
   1912 self.n_dispatched_batches += 1
   1913 self.n_dispatched_tasks += 1
-> 1914 res = func(*args, **kwargs)
   1915 self.n_completed_tasks += 1
   1916 self.print_progress()

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/memory.py:607, in MemorizedFunc.__call__(self, *args, **kwargs)
    605 def __call__(self, *args, **kwargs):
    606     # Return the output, without the metadata
--> 607     return self._cached_call(args, kwargs, shelving=False)[0]

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/memory.py:562, in MemorizedFunc._cached_call(self, args, kwargs, shelving)
    556     self.warn(
    557         f"Computing func {func_name}, argument hash {args_id} "
    558         f"in location {location}"
    559     )
    561 # Returns the output but not the metadata
--> 562 return self._call(call_id, args, kwargs, shelving)

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/joblib/memory.py:832, in MemorizedFunc._call(self, call_id, args, kwargs, shelving)
    830 self._before_call(args, kwargs)
    831 start_time = time.time()
--> 832 output = self.func(*args, **kwargs)
    833 return self._after_call(call_id, args, kwargs, shelving, output, start_time)

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:328, in _fetch_tile(tile_url, wait, max_retries, headers)
    327 def _fetch_tile(tile_url, wait, max_retries, headers: dict[str, str]):
--> 328     array = _retryer(tile_url, wait, max_retries, headers)
    329     return array

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:488, in _retryer(tile_url, wait, max_retries, headers)
    486     time.sleep(wait)
    487     max_retries -= 1
--> 488     request = _retryer(tile_url, wait, max_retries, headers)
    489 else:
    490     raise requests.HTTPError("Connection reset by peer too many times. "
    491                              f"Last message was: {request.status_code} "
    492                              f"Error: {request.reason} for url: {request.url}")

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:488, in _retryer(tile_url, wait, max_retries, headers)
    486     time.sleep(wait)
    487     max_retries -= 1
--> 488     request = _retryer(tile_url, wait, max_retries, headers)
    489 else:
    490     raise requests.HTTPError("Connection reset by peer too many times. "
    491                              f"Last message was: {request.status_code} "
    492                              f"Error: {request.reason} for url: {request.url}")

File ~/checkouts/readthedocs.org/user_builds/geopandas/conda/v1.1.4/lib/python3.13/site-packages/contextily/tile.py:490, in _retryer(tile_url, wait, max_retries, headers)
    488     request = _retryer(tile_url, wait, max_retries, headers)
    489 else:
--> 490     raise requests.HTTPError("Connection reset by peer too many times. "
    491                              f"Last message was: {request.status_code} "
    492                              f"Error: {request.reason} for url: {request.url}")

HTTPError: Connection reset by peer too many times. Last message was: 502 Error: Bad Gateway for url: https://a.tile.openstreetmap.fr/hot/12/1202/1536.png
../_images/gallery_plotting_basemap_background_15_1.png

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()
../_images/gallery_plotting_basemap_background_18_0.png

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)
../_images/gallery_plotting_basemap_background_21_0.png

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)
../_images/gallery_plotting_basemap_background_23_0.png