Reference Guide#

Plotting basemaps#

contextily.add_basemap(ax, zoom='auto', source=None, interpolation='bilinear', attribution=None, attribution_size=8, reset_extent=True, crs=None, resampling=Resampling.bilinear, zoom_adjust=None, **extra_imshow_args)#

Add a (web/local) basemap to ax.

Parameters:
axAxesSubplot

Matplotlib axes object on which to add the basemap. The extent of the axes is assumed to be in Spherical Mercator (EPSG:3857), unless the crs keyword is specified.

zoomint or ‘auto’

[Optional. Default=’auto’] Level of detail for the basemap. If ‘auto’, it is calculated automatically. Ignored if source is a local file.

sourcexyzservices.TileProvider object or str

[Optional. Default: OpenStreetMap Humanitarian web tiles] The tile source: web tile provider, a valid input for a query of a xyzservices.TileProvider by a name from xyzservices.providers or path to local file. The web tile provider can be in the form of a xyzservices.TileProvider object or a URL. The placeholders for the XYZ in the URL need to be {x}, {y}, {z}, respectively. For local file paths, the file is read with rasterio and all bands are loaded into the basemap. IMPORTANT: tiles are assumed to be in the Spherical Mercator projection (EPSG:3857), unless the crs keyword is specified.

interpolationstr

[Optional. Default=’bilinear’] Interpolation algorithm to be passed to imshow. See matplotlib.pyplot.imshow for further details.

attributionstr

[Optional. Defaults to attribution specified by the source] Text to be added at the bottom of the axis. This defaults to the attribution of the provider specified in source if available. Specify False to not automatically add an attribution, or a string to pass a custom attribution.

attribution_sizeint

[Optional. Defaults to ATTRIBUTION_SIZE]. Font size to render attribution text with.

reset_extentbool

[Optional. Default=True] If True, the extent of the basemap added is reset to the original extent (xlim, ylim) of ax

crsNone or str or CRS

[Optional. Default=None] coordinate reference system (CRS), expressed in any format permitted by rasterio, to use for the resulting basemap. If None (default), no warping is performed and the original Spherical Mercator (EPSG:3857) is used.

resampling<enum ‘Resampling’>

[Optional. Default=Resampling.bilinear] Resampling method for executing warping, expressed as a rasterio.enums.Resampling method

zoom_adjustint or None

[Optional. Default: None] The amount to adjust a chosen zoom level if it is chosen automatically. Values outside of -1 to 1 are not recommended as they can lead to slow execution.

**extra_imshow_args

Other parameters to be passed to imshow.

Examples

>>> import geopandas
>>> import contextily as cx
>>> db = geopandas.read_file(ps.examples.get_path('virginia.shp'))

Ensure the data is in Spherical Mercator:

>>> db = db.to_crs(epsg=3857)

Add a web basemap:

>>> ax = db.plot(alpha=0.5, color='k', figsize=(6, 6))
>>> cx.add_basemap(ax, source=url)
>>> plt.show()

Or download a basemap to a local file and then plot it:

>>> source = 'virginia.tiff'
>>> _ = cx.bounds2raster(*db.total_bounds, zoom=6, source=source)
>>> ax = db.plot(alpha=0.5, color='k', figsize=(6, 6))
>>> cx.add_basemap(ax, source=source)
>>> plt.show()
contextily.add_attribution(ax, text, font_size=8, **kwargs)#

Utility to add attribution text.

Parameters:
axAxesSubplot

Matplotlib axes object on which to add the attribution text.

textstr

Text to be added at the bottom of the axis.

font_sizeint

[Optional. Defaults to 8] Font size in which to render the attribution text.

**kwargsAdditional keywords to pass to the matplotlib text method.
Returns:
matplotlib.text.Text

Matplotlib Text object added to the plot.

Working with tiles#

contextily.bounds2raster(w, s, e, n, path, zoom='auto', source=None, ll=False, wait=0, max_retries=2, n_connections=1, use_cache=True)#

Take bounding box and zoom, and write tiles into a raster file in the Spherical Mercator CRS (EPSG:3857)

Parameters:
wfloat

West edge

sfloat

South edge

efloat

East edge

nfloat

North edge

zoomint

Level of detail

pathstr

Path to raster file to be written

sourcexyzservices.TileProvider object or str

[Optional. Default: OpenStreetMap Humanitarian web tiles] The tile source: web tile provider or path to local file. The web tile provider can be in the form of a xyzservices.TileProvider object or a URL. The placeholders for the XYZ in the URL need to be {x}, {y}, {z}, respectively. For local file paths, the file is read with rasterio and all bands are loaded into the basemap. IMPORTANT: tiles are assumed to be in the Spherical Mercator projection (EPSG:3857), unless the crs keyword is specified.

llBoolean

[Optional. Default: False] If True, w, s, e, n are assumed to be lon/lat as opposed to Spherical Mercator.

waitint

[Optional. Default: 0] if the tile API is rate-limited, the number of seconds to wait between a failed request and the next try

max_retries: int

[Optional. Default: 2] total number of rejected requests allowed before contextily will stop trying to fetch more tiles from a rate-limited API.

n_connections: int

[Optional. Default: 1] Number of connections for downloading tiles in parallel. Be careful not to overload the tile server and to check the tile provider’s terms of use before increasing this value. E.g., OpenStreetMap has a max. value of 2 (https://operations.osmfoundation.org/policies/tiles/). If allowed to download in parallel, a recommended value for n_connections is 16, and should never be larger than 64.

use_cache: bool

[Optional. Default: True] If False, caching of the downloaded tiles will be disabled. This can be useful in resource constrained environments, especially when using n_connections > 1, or when a tile provider’s terms of use don’t allow caching.

Returns:
imgndarray

Image as a 3D array of RGB values

extenttuple

Bounding box [minX, maxX, minY, maxY] of the returned image

contextily.bounds2img(w, s, e, n, zoom='auto', source=None, ll=False, wait=0, max_retries=2, n_connections=1, use_cache=True, zoom_adjust=None)#

Take bounding box and zoom and return an image with all the tiles that compose the map and its Spherical Mercator extent.

Parameters:
wfloat

West edge

sfloat

South edge

efloat

East edge

nfloat

North edge

zoomint

Level of detail

sourcexyzservices.TileProvider object or str

[Optional. Default: OpenStreetMap Humanitarian web tiles] The tile source: web tile provider or path to local file. The web tile provider can be in the form of a xyzservices.TileProvider object or a URL. The placeholders for the XYZ in the URL need to be {x}, {y}, {z}, respectively. For local file paths, the file is read with rasterio and all bands are loaded into the basemap. IMPORTANT: tiles are assumed to be in the Spherical Mercator projection (EPSG:3857), unless the crs keyword is specified.

llBoolean

[Optional. Default: False] If True, w, s, e, n are assumed to be lon/lat as opposed to Spherical Mercator.

waitint

[Optional. Default: 0] if the tile API is rate-limited, the number of seconds to wait between a failed request and the next try

max_retries: int

[Optional. Default: 2] total number of rejected requests allowed before contextily will stop trying to fetch more tiles from a rate-limited API.

n_connections: int

[Optional. Default: 1] Number of connections for downloading tiles in parallel. Be careful not to overload the tile server and to check the tile provider’s terms of use before increasing this value. E.g., OpenStreetMap has a max. value of 2 (https://operations.osmfoundation.org/policies/tiles/). If allowed to download in parallel, a recommended value for n_connections is 16, and should never be larger than 64.

use_cache: bool

[Optional. Default: True] If False, caching of the downloaded tiles will be disabled. This can be useful in resource constrained environments, especially when using n_connections > 1, or when a tile provider’s terms of use don’t allow caching.

zoom_adjustint or None

[Optional. Default: None] The amount to adjust a chosen zoom level if it is chosen automatically. Values outside of -1 to 1 are not recommended as they can lead to slow execution.

Returns:
imgndarray

Image as a 3D array of RGB values

extenttuple

Bounding box [minX, maxX, minY, maxY] of the returned image

contextily.warp_tiles(img, extent, t_crs='EPSG:4326', resampling=Resampling.bilinear)#

Reproject (warp) a Web Mercator basemap into any CRS on-the-fly

NOTE: this method works well with contextily’s bounds2img approach to

raster dimensions (h, w, b)

Parameters:
imgndarray

Image as a 3D array (h, w, b) of RGB values (e.g. as returned from contextily.bounds2img)

extenttuple

Bounding box [minX, maxX, minY, maxY] of the returned image, expressed in Web Mercator (EPSG:3857)

t_crsstr/CRS

[Optional. Default=’EPSG:4326’] Target CRS, expressed in any format permitted by rasterio. Defaults to WGS84 (lon/lat)

resampling<enum ‘Resampling’>

[Optional. Default=Resampling.bilinear] Resampling method for executing warping, expressed as a rasterio.enums.Resampling method

Returns:
imgndarray

Image as a 3D array (h, w, b) of RGB values (e.g. as returned from contextily.bounds2img)

exttuple

Bounding box [minX, maxX, minY, maxY] of the returned (warped) image

contextily.warp_img_transform(img, transform, s_crs, t_crs, resampling=Resampling.bilinear)#

Reproject (warp) an img with a given transform and s_crs into a different t_crs

NOTE: this method works well with rasterio’s .read() approach to raster’s dimensions (b, h, w)

Parameters:
imgndarray

Image as a 3D array (b, h, w) of RGB values (e.g. as returned from rasterio’s .read() method)

transformaffine.Affine

Transform of the input image as expressed by rasterio and the affine package

s_crsstr/CRS

Source CRS in which img is passed, expressed in any format permitted by rasterio.

t_crsstr/CRS

Target CRS, expressed in any format permitted by rasterio.

resampling<enum ‘Resampling’>

[Optional. Default=Resampling.bilinear] Resampling method for executing warping, expressed as a rasterio.enums.Resampling method

Returns:
w_imgndarray

Warped image as a 3D array (b, h, w) of RGB values (e.g. as returned from rasterio’s .read() method)

w_transformaffine.Affine

Transform of the input image as expressed by rasterio and the affine package

contextily.howmany(w, s, e, n, zoom, verbose=True, ll=False)#

Number of tiles required for a given bounding box and a zoom level

Parameters:
wfloat

West edge

sfloat

South edge

efloat

East edge

nfloat

North edge

zoomint

Level of detail

verboseBoolean

[Optional. Default=True] If True, print short message with number of tiles and zoom.

llBoolean

[Optional. Default: False] If True, w, s, e, n are assumed to be lon/lat as opposed to Spherical Mercator.

Geocoding and plotting places#

class contextily.Place(search, zoom=None, path=None, zoom_adjust=None, source=None, geocoder=<geopy.geocoders.nominatim.Nominatim object>)#

Geocode a place by name and get its map.

This allows you to search for a name (e.g., city, street, country) and grab map and location data from the internet.

Parameters:
searchstring

The location to be searched.

zoomint or None

[Optional. Default: None] The level of detail to include in the map. Higher levels mean more tiles and thus longer download time. If None, the zoom level will be automatically determined.

pathstr or None

[Optional. Default: None] Path to a raster file that will be created after getting the place map. If None, no raster file will be downloaded.

zoom_adjustint or None

[Optional. Default: None] The amount to adjust a chosen zoom level if it is chosen automatically.

sourcexyzservices.providers object or str

[Optional. Default: OpenStreetMap Humanitarian web tiles] The tile source: web tile provider or path to local file. The web tile provider can be in the form of a xyzservices.TileProvider object or a URL. The placeholders for the XYZ in the URL need to be {x}, {y}, {z}, respectively. For local file paths, the file is read with rasterio and all bands are loaded into the basemap. IMPORTANT: tiles are assumed to be in the Spherical Mercator projection (EPSG:3857), unless the crs keyword is specified.

geocodergeopy.geocoders

[Optional. Default: geopy.geocoders.Nominatim()] Geocoder method to process search

Attributes:
geocodegeopy object

The result of calling geopy.geocoders.Nominatim with search as input.

sfloat

The southern bbox edge.

nfloat

The northern bbox edge.

efloat

The eastern bbox edge.

wfloat

The western bbox edge.

imndarray

The image corresponding to the map of search.

bboxlist

The bounding box of the returned image, expressed in lon/lat, with the following order: [minX, minY, maxX, maxY]

bbox_maptuple

The bounding box of the returned image, expressed in Web Mercator, with the following order: [minX, minY, maxX, maxY]

Methods

plot([ax, zoom, interpolation, attribution])

Plot a Place object

Place.plot(ax=None, zoom='auto', interpolation='bilinear', attribution=None)#

Plot a Place object …

Parameters:
axAxesSubplot

Matplotlib axis with x_lim and y_lim set in Web Mercator (EPSG=3857). If not provided, a new 12x12 figure will be set and the name of the place will be added as title

zoomint/’auto’

[Optional. Default=’auto’] Level of detail for the basemap. If ‘auto’, if calculates it automatically. Ignored if source is a local file.

interpolationstr

[Optional. Default=’bilinear’] Interpolation algorithm to be passed to imshow. See matplotlib.pyplot.imshow for further details.

attributionstr

[Optional. Defaults to attribution specified by the source of the map tiles] Text to be added at the bottom of the axis. This defaults to the attribution of the provider specified in source if available. Specify False to not automatically add an attribution, or a string to pass a custom attribution.

Returns:
axAxesSubplot

Matplotlib axis with x_lim and y_lim set in Web Mercator (EPSG=3857) containing the basemap

Examples

>>> lvl = cx.Place('Liverpool')
>>> lvl.plot()
contextily.plot_map(place, bbox=None, title=None, ax=None, axis_off=True, latlon=True, attribution=None)#

Plot a map of the given place.

Parameters:
placeinstance of Place or ndarray

The map to plot. If an ndarray, this must be an image corresponding to a map. If an instance of Place, the extent of the image and name will be inferred from the bounding box.

axinstance of matplotlib Axes object or None

The axis on which to plot. If None, one will be created.

axis_offbool

Whether to turn off the axis border and ticks before plotting.

attributionstr

[Optional. Default to standard ATTRIBUTION] Text to be added at the bottom of the axis.

Returns:
axinstance of matplotlib Axes object or None

The axis on the map is plotted.