PyGMT Documentation

repository·main·Indexed 21 days ago

https://github.com/genericmappingtools/pygmt

A Python interface for the Generic Mapping Tools (GMT) used for processing geospatial and geophysical data to create publication-quality maps and figures. It integrates with the scientific Python ecosystem, supporting numpy, pandas, xarray, and geopandas, and provides a direct interface to the GMT C API via ctypes. Key features include the Figure class for plotting, built-in GMT datasets, and support for Jupyter notebooks.

Tokens
27K
Snippets
66
Records
107
Agent score
73%

What's inside PyGMT

  1. What is PyGMT?

    main

    PyGMT is a Python wrapper for the Generic Mapping Tools (GMT). It is designed for processing spatial data (such as gridding, filtering, masking, and FFTs) and generating high-quality maps and plots.

    Unlike interactive libraries like Bokeh or Matplotlib, PyGMT leverages GMT's ability to generate high-quality, static vector graphics using the PostScript format. This makes it highly memory-efficient and fast, making it suitable for publication-quality figures, posters, and talks. While the underlying engine uses PostScript, users typically interact with more convenient formats like PDF, PNG, and JPG.

  2. Core concepts of PyGMT

    main

    PyGMT is a Pythonic interface for the Generic Mapping Tools (GMT). It is designed to facilitate the processing of geospatial and geophysical data for creating publication-quality maps.

    Key architectural features include:

    • Direct GMT C API Interface: It uses ctypes to interface with the GMT C API directly, avoiding the overhead of system calls.
    • Scientific Python Integration: It is built to work seamlessly with the scientific Python ecosystem, supporting data structures like numpy.ndarray or pandas.DataFrame for tables, xarray.DataArray for grids, and geopandas.GeoDataFrame for geographical data.
    • Jupyter Support: It provides rich display capabilities within Jupyter notebooks.
  3. Manage PyGMT repository branches

    main

    The repository uses two primary branches:

    • main: The stable branch. It is always tested and ready for release. Do not push directly to this branch. All changes must be submitted via a new branch and a pull request.
    • gh-pages: Used for hosting HTML documentation via GitHub Pages. This branch is automatically updated by GitHub Actions, so manual commits are not required.
  4. Use Class-style Parameters and Enums

    main

    PyGMT uses specialized classes and enums to provide structured configuration for plotting and data handling.

    Class-style Parameters (pygmt.params):

    • Axis, Box, Frame, Pattern, Position.

    Enums (pygmt.enums):

    • GridRegistration: Controls how grids are registered.
    • GridType: Defines the type of grid being used.
  5. Use TODO comments for temporary code and deprecations

    main

    TODO comments are used to track temporary code, such as workarounds for GMT versions or parameters scheduled for removal. They must follow a specific format to indicate when the item should be addressed:

    # TODO(package>=X.Y.Z): A brief description of the TODO item.

    Note: Do not use TODO comments to track unimplemented features; use GitHub Issues for that purpose.

    # TODO(package>=X.Y.Z): A brief description of the TODO item.
    # Additional details if necessary.
  6. Specify fonts in PyGMT

    main

    PyGMT supports 35 standard PostScript fonts. When using text-related methods (like fig.text), you can specify a font using either its font name (as a string) or its font number (as an integer).

    For example, to use the font "Helvetica", you can use either "Helvetica" or 0.

    Special Fonts: For the special fonts Symbol (number 12) and ZapfDingbats (number 34), refer to the character encoding documentation for their specific character sets.

    # Using font name
    fig.text(x=1, y=1, text="Hello", font="Helvetica")
    
    # Using font number
    fig.text(x=1, y=1, text="Hello", font="0")
  7. Plotting with the Figure class

    main

    All plotting in PyGMT is managed through the pygmt.Figure class. You create a figure instance and call its methods to add various elements to the map.

    Common tasks include:

    • Adding figure elements: basemap, coast, colorbar, legend, scalebar, text, etc.
    • Plotting tabular data: plot, contour, histogram, meca, rose, etc.
    • Plotting raster data: grdimage, grdcontour, grdview, image, etc.
    • Configuring layout: subplot, set_panel, shift_origin.
    • Output: savefig to save the figure, show to display it, and psconvert for PostScript conversion.
    import pygmt
    
    fig = pygmt.Figure()
    fig.basemap(region="W/E/S/N", projection="M15c", coast="F")
    fig.coast("W/E/S/N", shore="black")
    fig.savefig("map.png")
  8. Use justification codes to position plot embellishments

    main

    To place embellishments (such as scalebars, colorbars, legends, text, or images) on a figure, PyGMT requires two points: a reference point on the figure and an anchor point on the feature.

    Justification codes are two-character strings used to define these points. They consist of one vertical code and one horizontal code (the order of characters does not matter).

    Vertical codes:

    • T: Top
    • M: Middle
    • B: Bottom

    Horizontal codes:

    • L: Left
    • C: Centre
    • R: Right

    Example: "TL" refers to Top Left.

    For non-rectangular geographic basemaps, justification codes refer to the invisible, rectangular bounding box of the map.

    import pygmt
    
    # Example of using justification codes in a text call
    fig = pygmt.Figure()
    fig.basemap(projection="X10c/6c", region=[-5, 5, -5, 5], frame=0)
    
    fig.text(
        font="15p,1,black",
        x=0,
        y=0,
        text="Centered Text",
        justify="MC",  # Middle Centre
        offset="j0.5c/0.5c+v2p,gray30",
    )
    
    fig.show()
  9. How contributors are recognized in PyGMT releases

    main

    PyGMT uses several methods to provide recognition for human contributors (bots and AI tools are not considered authors; the human reviewer is the recognized author):

    • AUTHORS.md: A file in the repository listing PyGMT Developers. Anyone who has contributed a pull request is welcome to add themselves.
    • Changelog: Every release includes a changelog mentioning everyone who contributed (commits or PR reviews) since the previous release. GitHub full names are used if available; otherwise, GitHub handles are used.
    • Zenodo Archives: Contributors appearing in git log are invited to be authors on Zenodo archives if they provide their details in AUTHORS.md.
    • CITATION.cff: Authors included in the Zenodo archive are also listed in the CITATION.cff file to facilitate easy citation of the software.
  10. Specify map projections in PyGMT

    main

    PyGMT supports a wide variety of map projections. To use a specific projection, pass the projection parameter to PyGMT plotting methods.

    Projections are specified using a one-letter code, followed by optional reference longitude and latitude, and the map width. The map height is automatically calculated by PyGMT based on the specified region and the chosen projection.

    Syntax Pattern: projection='CODE[lon0/lat0[/horizon]]/width'

    • CODE: A one-letter code representing the projection type.
    • lon0/lat0: (Optional) Reference longitude and latitude.
    • horizon: (Optional) A flag used with specific projections.
    • width: The width of the map.
  11. Understand Dimension vs. Distance Units in PyGMT

    main

    PyGMT distinguishes between two types of units to ensure accuracy in mapping and geospatial analysis:

    1. Dimension Units (Plot Units): Used for physical map dimensions, such as symbol sizes, pen widths, and map scales. These are relative to the output medium (e.g., paper or screen).
    2. Distance Units: Used for geographic calculations and representing real-world distances on the Earth's surface (e.g., coordinates or distance between points).
  12. Quickstart installation with conda

    main

    The fastest way to install PyGMT is using the conda package manager. This method automatically sets up a virtual environment and installs GMT along with all necessary dependencies.

    1. Create the environment:
      conda create --name pygmt --channel conda-forge pygmt
    2. Activate the environment:
      conda activate pygmt
    3. Verify the installation in a Python interpreter:
      import pygmt
      pygmt.show_versions()
    conda create --name pygmt --channel conda-forge pygmt
    conda activate pygmt