contextily

repository·main·Indexed 20 days ago

https://github.com/geopandas/contextily

A Python package for retrieving web tile maps to use as basemaps for matplotlib visualizations or as standalone geospatial raster files. It supports bounding boxes in WGS84 (EPSG:4326) and Spheric Mercator (EPSG:3857), providing functions like add_basemap, add_attribution, and bounds2raster. The library includes a Place class for geocoding and map generation, and utilities for warping tiles and managing tile caches.

Tokens
4.3K
Snippets
15
Records
21
Agent score
70%

What's inside contextily

  1. Overview of contextily capabilities

    main

    contextily is a Python package used to retrieve tile maps from the internet.

    Key capabilities include:

    • Adding tile maps as basemaps to matplotlib figures.
    • Writing tile maps to disk as geospatial raster files.
    • Supporting bounding boxes in both WGS84 (EPSG:4326) and Spheric Mercator (EPSG:3857).

    Tile providers are sourced from the xyzservices package, including OpenStreetMap and Stamen Design (Toner, Terrain, and Watercolor).

  2. How contextily, osmnx, and cenpy work together for urban mapping

    main

    contextily is often used as the final step in a mapping workflow involving other geospatial packages. A common pattern for urban data science is:

    1. Data Acquisition: Use cenpy to retrieve US Census/ACS data or osmnx to retrieve OpenStreetMap street networks using place-oriented queries (e.g., from_place('City, ST')).
    2. Data Harmonization: Convert different data representations (like osmnx's networkx graphs) into geopandas GeoDataFrames using osmnx.graph_to_gdfs.
    3. Coordinate Alignment: Use .to_crs() to ensure all GeoDataFrames share the same Coordinate Reference System (CRS). For contextily basemaps, it is recommended to use Web Mercator.
    4. Visualization: Plot the layers using matplotlib and call contextily.add_basemap() to provide geographic context.
  3. Geocoding and plotting places with contextily.Place

    main

    The contextily.Place class allows you to represent specific geographic locations. You can use the .plot() method on a Place instance to visualize the location on a map.

    import contextily as ctx
    # Assuming 'place' is an instance of contextily.Place
    place.plot(ax=ax)
  4. Working with tiles and raster conversion

    main

    Contextily provides utilities for converting geographic bounds to raster images and warping tiles. Key functions include:

    • contextily.bounds2raster: Converts geographic bounds to a raster format.
    • contextily.bounds2img: Converts geographic bounds to an image.
    • contextily.warp_tiles: Warps tiles to a new projection or extent.
    • contextily.warp_img_transform: Handles image transformations during warping.
    • contextily.howmany: Calculates the number of tiles required for a given area.
  5. Plotting basemaps with contextily.add_basemap

    main

    Use contextily.add_basemap to add a background tile layer (basemap) to an existing Matplotlib axes object. This is the primary way to provide geographic context to your plots.

    import contextily as ctx
    # Assuming 'ax' is a matplotlib axes object from a geopandas plot
    ctx.add_basemap(ax, source=ctx.providers.OpenStreetMap.Mapnik)
  6. Reproject an image with a given transform using warp_img_transform()

    main

    Use warp_img_transform() to reproject an image that follows the rasterio convention (bands, height, width) using an explicit affine transform.

    Parameters:

    • img: ndarray (3D array of shape (b, h, w)).
    • transform: affine.Affine object representing the input image transform.
    • s_crs: Source CRS.
    • t_crs: Target CRS.
    • resampling: rasterio.enums.Resampling method.

    Returns:

    • w_img: Warped ndarray (3D array of shape (b, h, w)).
    • w_transform: The new affine transform for the warped image.
    # Example usage for rasterio-style (b, h, w) arrays
    # warped_img, warped_transform = cx.warp_img_transform(img, transform, s_crs, t_crs)
  7. Configure the tile cache directory with set_cache_dir()

    main

    By default, contextily caches downloaded tiles in a temporary directory that is deleted when the Python session ends. To persist tiles across sessions, use set_cache_dir() to specify a custom path.

    Parameters:

    • path: String path to the directory where tiles should be stored.
    import contextily as cx
    
    # Set a persistent cache directory
    cx.set_cache_dir("/path/to/your/cache")
  8. Calculate the number of tiles required with howmany()

    main

    Use howmany() to estimate how many tiles will be downloaded for a given bounding box and zoom level. This is useful for estimating download time or bandwidth usage.

    Parameters:

    • w, s, e, n: Bounding box edges.
    • zoom: Zoom level (integer or 'auto').
    • verbose: If True, prints the count to the console.
    • ll: If True, coordinates are lon/lat.

    Returns:

    • int: The number of tiles required.
    import contextily as cx
    
    # Check how many tiles will be downloaded
    count = cx.howmany(w=-122.5, s=37.7, e=-122.3, n=37.8, zoom="auto")
  9. Reproject a Web Mercator basemap with warp_tiles()

    main

    Use warp_tiles() to reproject a Web Mercator (EPSG:3857) basemap into a different Coordinate Reference System (CRS) on-the-fly. This works specifically with the output format of bounds2img().

    Parameters:

    • img: ndarray (3D array of RGB values from bounds2img).
    • extent: Bounding box [minX, maxX, minY, maxY] of the input image in EPSG:3857.
    • t_crs: Target CRS (e.g., 'EPSG:4326').
    • resampling: A rasterio.enums.Resampling method (defaults to bilinear).

    Returns:

    • img: Warped ndarray (3D array of RGB values).
    • ext: Bounding box of the warped image.
    import contextily as cx
    from rasterio.enums import Resampling
    
    # Assuming img and extent were obtained from bounds2img()
    warped_img, warped_ext = cx.warp_tiles(
        img, 
        extent, 
        t_crs='EPSG:4326', 
        resampling=Resampling.bilinear
    )
  10. Add attribution text to a matplotlib plot with add_attribution()

    main

    The add_attribution function is a utility to add attribution text at the bottom of a Matplotlib axis. It uses a white stroke (path effect) to ensure the text remains readable over various basemap colors and handles text wrapping within the axis extent.

    Parameters

    • ax: The Matplotlib AxesSubplot object.
    • text: The string to display.
    • font_size: int (default: 8).
    • **kwargs: Any additional keyword arguments passed to the underlying matplotlib.text method.
    from contextily import add_attribution
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.text(0.5, 0.5, 'Hello World')
    
    # Add attribution to the bottom
    add_attribution(ax, "Data © OpenStreetMap contributors", font_size=10)
    
    plt.show()