# 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:
    ax AxesSubplot

      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.

    zoom int or ‘auto’

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

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

    interpolation str

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

    attribution str

      [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_size int

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

    reset_extent bool

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

    crs None 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_adjust int 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:
    ax AxesSubplot

      Matplotlib axes object on which to add the attribution text.

    text str

      Text to be added at the bottom of the axis.

    font_size int

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

    **kwargs Additional 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:
    w float

      West edge

    s float

      South edge

    e float

      East edge

    n float

      North edge

    zoom int

      Level of detail

    path str

      Path to raster file to be written

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

    ll Boolean

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

    wait int

      [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:
    img ndarray

      Image as a 3D array of RGB values

    extent tuple

      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:
    w float

      West edge

    s float

      South edge

    e float

      East edge

    n float

      North edge

    zoom int

      Level of detail

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

    ll Boolean

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

    wait int

      [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_adjust int 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:
    img ndarray

      Image as a 3D array of RGB values

    extent tuple

      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:
    img ndarray

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

    extent tuple

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

    t_crs str/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:
    img ndarray

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

    ext tuple

      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:
    img ndarray

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

    transform affine.Affine

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

    s_crs str/CRS

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

    t_crs str/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_img ndarray

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

    w_transform affine.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:
    w float

      West edge

    s float

      South edge

    e float

      East edge

    n float

      North edge

    zoom int

      Level of detail

    verbose Boolean

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

    ll Boolean

      [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:
    search string

      The location to be searched.

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

    path str 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_adjust int or None

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

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

    geocoder geopy.geocoders

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

  Attributes:
    geocode geopy object

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

    s float

      The southern bbox edge.

    n float

      The northern bbox edge.

    e float

      The eastern bbox edge.

    w float

      The western bbox edge.

    im ndarray

      The image corresponding to the map of `search`.

    bbox list

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

    bbox_map tuple

      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:
    ax AxesSubplot

      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

    zoom int/’auto’

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

    interpolation str

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

    attribution str

      [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:
    ax AxesSubplot

      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:
    place instance 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.

    ax instance of matplotlib Axes object or None

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

    axis_off bool

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

    attribution str

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

  Returns:
    ax instance of matplotlib Axes object or None

      The axis on the map is plotted.