Cartopy Documentation

repository·main·Indexed 23 days ago

https://github.com/scitools/cartopy

A Python library for cartographic visualizations integrated with Matplotlib. Cartopy provides object-oriented projection definitions, coordinate transformations for geospatial data, and vector data handling via Shapely. It is designed for producing publication-quality maps and performing geospatial data analysis, relying on PROJ, NumPy, and Shapely.

Tokens
33.1K
Snippets
67
Records
269
Agent score
81%

What's inside Cartopy

  1. Overview of Cartopy

    main

    Cartopy is a Python package designed to simplify drawing maps for data analysis and visualization. It provides several core capabilities for geospatial mapping:

    • Object-oriented projection definitions: Define and manage map projections as objects.
    • Transformations: Handle transformations for points, lines, polygons, and images between different projections.
    • Matplotlib Integration: Exposes advanced mapping features through a simple and intuitive interface within Matplotlib.
    • Vector Data Handling: Integrates shapefile reading with Shapely capabilities for powerful vector data manipulation.
  2. Introduction to Cartopy

    main

    Cartopy is a Python package for geospatial data processing, specifically designed for producing maps and performing geospatial data analyses. It provides a programmatic interface built on top of Matplotlib to create publication-quality maps.

    Key capabilities include:

    • Object-oriented projection definitions: Define and manage various map projections.
    • Coordinate transformations: Transform points, lines, vectors, polygons, and images between different projections.
    • Handling spherical data: Specifically designed to handle large-area/small-scale data where traditional Cartesian assumptions fail (e.g., avoiding singularities at the poles or issues at the dateline).

    Cartopy relies on the following libraries:

    • PROJ
    • NumPy
    • Shapely
  3. Access the Cartopy API reference

    main

    The Cartopy API reference provides detailed documentation for functions, modules, and objects. The reference is organized into several key sub-modules:

    • crs: Coordinate Reference Systems.
    • io: Input/Output operations.
    • matplotlib: Integration with Matplotlib for map plotting.
    • feature: Geographic features (e.g., coastlines, land, rivers).
    • transformations: Coordinate transformations.
    • config: Configuration settings.
  4. How the `projection` and `transform` keywords work together

    main

    In Cartopy, the projection and transform keyword arguments serve two distinct, independent purposes:

    1. projection: Used when creating axes (e.g., plt.axes(projection=...)). It determines the map projection of the plot itself—how the Earth is visually represented on your screen (e.g., ccrs.PlateCarree(), ccrs.NorthPolarStereo()).

    2. transform: Used within plotting functions (e.g., ax.contourf(..., transform=...)). It tells Cartopy the coordinate system in which your data is defined.

    Crucial Rule: If you do not provide a transform argument, Cartopy assumes your data is defined in the same coordinate system as the plot's projection. If your data is actually in latitude/longitude but your plot is in a different projection (like ccrs.RotatedPole), omitting transform will result in incorrectly placed data. To ensure accuracy, always explicitly provide the transform that matches your data's source coordinate system.

  5. Extend data acquisition with the Downloader API

    main

    To keep the core Cartopy release size small, most data is not included by default. Developers can implement new features that require external data by extending the cartopy.io.Downloader class. This class provides a standardized way to acquire data from external sources (typically via HTTP) while allowing users to configure their own acquisition methods.

    Existing subclasses of cartopy.io.Downloader include:

    • cartopy.io.shapereader.NEShpDownloader: Downloads zipped shapefiles from Natural Earth.
    • cartopy.io.srtm.SRTMDownloader: Downloads SRTM data.
  6. Perform geodesic calculations with cartopy.geodesic

    main
    For calculations involving distances, bearings, and paths on a curved surface (like the Earth), use the cartopy.geodesic module. The primary interface is the Geodesic class, which allows you to compute properties along the shortest path between points on a geoid or ellipsoid.
  7. Plot points and text using Geodetic transformations

    main

    When plotting specific geographic points (like a city) or labels on a map, use transform=ccrs.Geodetic() to ensure the coordinates are interpreted as latitude/longitude, regardless of the map's projection.

    # Example of marking a known place
    ax.plot(-117.1625, 32.715, 'bo', markersize=7, transform=ccrs.Geodetic())
    ax.text(-117, 33, 'San Diego', transform=ccrs.Geodetic())
  8. Implement raster data sources using RasterSource

    main

    Cartopy separates the retrieval of raster data from its visualization. To create a new source for raster data (such as a web service), you should implement an interface that follows the cartopy.io.RasterSource abstraction.

    Specifically, any object that implements the following two methods can be used as a source for 'slippy maps' (interactive, panning, and zooming maps):

    1. validate_projection: Ensures the projection is compatible.
    2. fetch_raster: Retrieves the image data given the necessary context (projection, extent, resolution, etc.).
  9. Use the Globe class to define ellipsoids

    main
    The cartopy.crs.Globe class is used to encapsulate the underlying sphere or ellipsoid of any Cartopy CRS. While most CRSs use the default Globe (representing the 'wgs84' reference ellipsoid), you can use this class to define custom planetary or ellipsoidal shapes for your coordinate systems.
  10. Add data to a map using the `transform` keyword

    main

    When adding data (points, lines, text) to a GeoAxes, you must specify the coordinate system of your data using the transform keyword.

    By default, Matplotlib assumes your data is in the same coordinate system as the map projection. However, most geographic data is provided in standard latitude/longitude coordinates. To plot this correctly, use an appropriate cartopy.crs.CRS instance (such as ccrs.PlateCarree() or ccrs.Geodetic()) in the transform argument of Matplotlib functions like plt.plot() or plt.text().

    Key distinction:

    • ccrs.PlateCarree(): Represents a standard lat/lon projection where lines are drawn as straight lines in 2D Cartesian space.
    • ccrs.Geodetic(): Represents a truly spherical coordinate system where lines are drawn as the shortest path (great circle) on the globe.
    import cartopy.crs as ccrs
    import matplotlib.pyplot as plt
    
    ax = plt.axes(projection=ccrs.PlateCarree())
    ax.stock_img()
    
    ny_lon, ny_lat = -75, 43
    delhi_lon, delhi_lat = 77.23, 28.61
    
    # Plotting a great circle path (curved on a flat map)
    plt.plot([ny_lon, delhi_lon], [ny_lat, delhi_lat],
             color='blue', linewidth=2, marker='o',
             transform=ccrs.Geodetic(),
             )
    
    # Plotting a straight line in lat/lon space
    plt.plot([ny_lon, delhi_lon], [ny_lat, delhi_lat],
             color='gray', linestyle='--',
             transform=ccrs.PlateCarree(),
             )
    
    plt.text(ny_lon - 3, ny_lat - 12, 'New York',
             horizontalalignment='right',
             transform=ccrs.Geodetic())
    
    plt.text(delhi_lon + 3, delhi_lat - 12, 'Delhi',
             horizontalalignment='left',
             transform=ccrs.Geodetic())
    
    plt.show()