Reference Guide

Plotting basemaps

contextily.add_basemap(ax, zoom='auto', url=None, interpolation='bilinear', attribution=None, attribution_size=8, reset_extent=True, crs=None, resampling=<Resampling.bilinear: 1>, \*\*extra_imshow_args)

Add a (web/local) basemap to ax.

Parameters
axAxesSubplot

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

zoomint/’auto’

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

urlstr

[Optional. Default: ‘http://tile.stamen.com/terrain/tileZ/tileX/tileY.png’] Source url for web tiles, or path to local file. If local, the file is read with rasterio and all bands are loaded into the basemap.

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 url] Text to be added at the bottom of the axis. This defaults to the attribution of the provider specified in url 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_extentBoolean

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

crsNone/str/CRS

[Optional. Default=None] CRS, expressed in any format permitted by rasterio, to use for the resulting basemap. If None (default), no warping is performed and the original Web Mercator (EPSG:3857, {‘init’ :’epsg:3857’}) is used.

resampling<enum ‘Resampling’>

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

**extra_imshow_args :

Other parameters to be passed to imshow.

Examples

>>> db = gpd.read_file(ps.examples.get_path('virginia.shp'))                .to_crs(epsg=3857)

Add a web basemap:

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

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

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

Utility to add attribution text.

Parameters
axAxesSubplot

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

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, url=None)

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

sourcecontextily.tile or str

[Optional. Default: ‘http://tile.stamen.com/terrain/tileZ/tileX/tileY.png’] URL for tile provider. The placeholders for the XYZ need to be tileX, tileY, tileZ, respectively. IMPORTANT: tiles are assumed to be in the Spherical Mercator projection (EPSG:3857).

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.

urlstr [DEPRECATED]

[Optional. Default: ‘http://tile.stamen.com/terrain/tileZ/tileX/tileY.png’] URL for tile provider. The placeholders for the XYZ need to be tileX, tileY, tileZ, respectively. See cx.sources.

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, url=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

sourcecontextily.tile or str

[Optional. Default: ‘http://tile.stamen.com/terrain/tileZ/tileX/tileY.png’] URL for tile provider. The placeholders for the XYZ need to be tileX, tileY, tileZ, respectively. IMPORTANT: tiles are assumed to be in the Spherical Mercator projection (EPSG:3857).

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.

urlstr [DEPRECATED]

[Optional. Default: ‘http://tile.stamen.com/terrain/tileZ/tileX/tileY.png’] URL for tile provider. The placeholders for the XYZ need to be tileX, tileY, tileZ, respectively. IMPORTANT: tiles are assumed to be in the Spherical Mercator projection (EPSG:3857).

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

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

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, url=None)

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

pathstring | 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 | None

The amount to adjust a chosen zoom level if it is chosen automatically.

urlstring

The URL to use for downloading map tiles. See the cx.tile_providers module for some options, as well as cx.bounds2image for guidance.

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(self[, ax, zoom, interpolation, …])

Plot a Place object

Place.plot(self, 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 url 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 url] Text to be added at the bottom of the axis. This defaults to the attribution of the provider specified in url 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 = ctx.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 | 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 | 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 | None

The axis on the map is plotted.