Note

Interactive online version:

# 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, Stamen).

[1]:

import geopandas


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(geopandas.datasets.get_path('nybb'))
ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')


# Convert the data to Web Mercator¶

Web map tiles are typically provided in Web Mercator (EPSG 3857), so we need to make sure to convert our data first to the same CRS to combine our polygons and background tiles in the same map:

[3]:

df = df.to_crs(epsg=3857)

[4]:

import contextily as ctx


# Add background tiles to plot¶

We can use add_basemap function of contextily to easily add a background map to our plot. :

[5]:

ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')


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).:

[6]:

ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')


By default, contextily uses the Stamen Terrain style. We can specify a different style using ctx.providers:

[7]:

ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k')

<ipython-input-1-f949b99ddd50>:2: FutureWarning: The "url" option is deprecated. Please use the "source" argument instead.

[ ]: