CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pygmt

A Python interface for the Generic Mapping Tools

Pending
Overview
Eval results
Files

figure-plotting.mddocs/

Figure and Plotting

Core plotting interface providing all GMT visualization capabilities. The Figure class serves as the main plotting canvas and provides methods for creating basemaps, plotting data, adding annotations, and managing figure display and output.

Capabilities

Figure Management

Create and manage GMT figures with display and output capabilities.

class Figure:
    def __init__(self) -> None:
        """Initialize a new Figure instance with unique name and preview directory."""
    
    @property
    def region(self) -> np.ndarray:
        """Return the geographic WESN bounding box for the current figure."""
    
    def show(self, method: Literal["external", "notebook", "none", None] = None, 
             dpi: int = 300, width: int = 500, waiting: float = 0.5, **kwargs) -> None:
        """
        Display a preview of the figure.
        
        Parameters:
        - method: Display method ("external", "notebook", "none", or None for default)
        - dpi: Image resolution for notebook display
        - width: Image width in pixels for notebook display  
        - waiting: Wait time after launching external viewer
        """
    
    def savefig(self, fname: PathLike, transparent: bool = False, crop: bool = True,
                anti_alias: bool = True, show: bool = False, worldfile: bool = False, 
                **kwargs) -> None:
        """
        Save the figure to an image file.
        
        Parameters:
        - fname: Output file path with extension (BMP, JPEG, GeoTIFF, PNG, PPM, TIFF, EPS, PDF, KML)
        - transparent: Enable transparent background (PNG/KML only)
        - crop: Crop figure canvas to plot area
        - anti_alias: Enable anti-aliasing for raster images
        - show: Display figure in external viewer after saving
        - worldfile: Create companion world file for georeferencing
        """

Basic Mapping and Plotting

Fundamental mapping functions for creating basemaps, coastlines, and data plots.

def basemap(self, **kwargs) -> None:
    """
    Plot base maps and frames.
    
    Parameters (via kwargs):
    - region: Required if this is the first plot command [west, east, south, north]
    - projection: Map projection (e.g., "M15c", "X10c/8c")
    - frame: Frame/axes configuration (bool or str)
    - map_scale: Draw a simple map scale (str)
    - rose: Draw a map directional rose (str) 
    - compass: Draw a map magnetic rose (str)
    """

def coast(self, resolution: Literal["auto", "full", "high", "intermediate", "low", "crude", None] = None, 
          **kwargs) -> None:
    """
    Plot continents, countries, shorelines, rivers, and borders.
    
    Parameters:
    - resolution: Coastline dataset resolution
    - region: Geographic extent [west, east, south, north]
    - projection: Map projection
    - frame: Frame configuration
    - land: Fill color/pattern for dry areas (str)
    - water: Fill color/pattern for wet areas (str)
    - shorelines: Draw shorelines (bool, int, str, or list)
    - rivers: Draw rivers (int, str, or list)
    - borders: Draw political boundaries (int, str, or list)
    - area_thresh: Area threshold for features
    """

def plot(self, data: PathLike | TableLike | None = None, x=None, y=None, size=None,
         symbol=None, direction=None, straight_line: bool | Literal["x", "y"] = False, 
         **kwargs) -> None:
    """
    Plot lines, polygons, and symbols in 2-D.
    
    Parameters:
    - data: File name or data table (dict, array, DataFrame, etc.)
    - x: x coordinates or arrays
    - y: y coordinates or arrays  
    - size: Size of data points (1-D array)
    - symbol: Symbols for data points (1-D array)
    - direction: Vector directions (list of two 1-D arrays)
    - straight_line: Control line segment drawing
    - region: Geographic extent
    - projection: Map projection
    - style: Plot symbols/vectors (str)
    - pen: Pen attributes for outlines
    - fill: Fill color (can be 1-D array)
    - cmap: Color palette for colored symbols
    """

def plot3d(self, data: PathLike | TableLike | None = None, **kwargs) -> None:
    """
    Plot lines, polygons, and symbols in 3-D.
    
    Parameters:
    - data: File name or 3-D data table
    - region: 3-D extent [west, east, south, north, bottom, top]
    - projection: Map projection
    - zscale/zsize: Z-axis scaling or size
    - perspective: 3-D perspective parameters
    - style: 3-D plot symbols/vectors
    """

Grid and Image Display

Functions for displaying grids, images, and creating contour maps.

def grdimage(self, grid: PathLike | xr.DataArray, **kwargs) -> None:
    """
    Project and plot grids or images.
    
    Parameters:
    - grid: 2-D grid file path or xarray DataArray
    - region: Geographic extent
    - projection: Map projection  
    - frame: Frame configuration
    - cmap: Color palette (str)
    - shading: Illumination/intensity grid (str or xr.DataArray)
    - nan_transparent: Make NaN values transparent (bool or str)
    - no_clip: Control clipping at boundaries (bool)
    - dpi: Resolution of projected grid (int)
    """

def grdview(self, grid: PathLike | xr.DataArray, **kwargs) -> None:
    """
    Create 3-D perspective image or surface mesh from a grid.
    
    Parameters:
    - grid: 2-D grid file or xarray DataArray
    - region: 3-D extent
    - projection: Map projection
    - zscale/zsize: Z-axis scaling
    - perspective: 3-D viewing parameters
    - cmap: Color palette
    - shading: Illumination grid
    - surftype: Surface type (surface/mesh/image)
    """

def grdcontour(self, grid: PathLike | xr.DataArray, **kwargs) -> None:
    """
    Make contour map using a grid.
    
    Parameters:
    - grid: 2-D grid file or xarray DataArray
    - region: Geographic extent
    - projection: Map projection
    - frame: Frame configuration
    - interval: Contour interval (str or number)
    - levels: Specific contour levels (list)
    - cmap: Color palette for filled contours
    - pen: Pen attributes for contour lines  
    - label: Contour labeling options
    """

def contour(self, data: PathLike | TableLike | None = None, x=None, y=None, z=None, 
            **kwargs) -> None:
    """
    Contour table data by direct triangulation.
    
    Parameters:
    - data: File name or data table with x, y, z columns
    - x, y, z: Coordinate and data arrays
    - region: Geographic extent
    - projection: Map projection
    - interval: Contour interval
    - levels: Specific contour levels
    - triangulate: Triangulation method
    """

def image(self, imagefile: PathLike, **kwargs) -> None:
    """
    Place images or EPS files on maps.
    
    Parameters:
    - imagefile: Path to image file
    - region: Geographic extent  
    - projection: Map projection
    - position: Image position and size
    - justify: Image justification
    - box: Draw border around image
    """

Data Visualization

Specialized plotting functions for different data types and visualization needs.

def histogram(self, data: PathLike | TableLike, **kwargs) -> None:
    """
    Plot a histogram.
    
    Parameters:  
    - data: Data file or array
    - region: Plot extent
    - projection: Plot projection
    - series: Histogram range and bin width
    - pen: Pen attributes for histogram bars
    - fill: Fill color for bars
    - horizontal: Create horizontal histogram
    """

def ternary(self, data: PathLike | TableLike | None = None, **kwargs) -> None:
    """
    Plot data on ternary diagrams.
    
    Parameters:
    - data: Data file or table with 3 components
    - region: Ternary plot extent  
    - frame: Ternary axes configuration
    - style: Symbol style for data points
    - cmap: Color palette
    """

def rose(self, data: PathLike | TableLike | None = None, **kwargs) -> None:
    """
    Plot a polar histogram (rose diagram).
    
    Parameters:
    - data: Angular data file or array
    - region: Angular extent
    - frame: Circular frame configuration
    - sector: Angular sector width
    - radial_scale: Radial axis scaling
    - pen: Pen attributes
    - fill: Fill color
    """

def wiggle(self, data: PathLike | TableLike | None = None, **kwargs) -> None:
    """
    Plot z = f(x,y) anomalies along tracks.
    
    Parameters:
    - data: Track data with x, y, z columns
    - region: Geographic extent
    - projection: Map projection
    - scale: Amplitude scaling
    - pen: Pen attributes for wiggle traces
    - fill: Fill colors (positive/negative)
    """

Specialized Geophysical Plotting

Functions for plotting geophysical and geological data.

def velo(self, data: PathLike | TableLike | None = None, **kwargs) -> None:
    """
    Plot velocity vectors, crosses, anisotropy bars and wedges.
    
    Parameters:
    - data: Velocity data file or table
    - region: Geographic extent
    - projection: Map projection
    - vector: Vector symbol specification
    - pen: Pen attributes for vectors
    - fill: Fill color for symbols
    - uncertainty: Plot error ellipses
    """

def meca(self, spec: PathLike | TableLike | None = None, **kwargs) -> None:
    """
    Plot focal mechanisms.
    
    Parameters:
    - spec: Focal mechanism data file or table
    - region: Geographic extent
    - projection: Map projection  
    - convention: Focal mechanism convention (aki/gcmt/partial/principal/mt/dc)
    - scale: Symbol scaling
    - pen: Pen attributes
    - fill: Fill color for compressive quadrants
    """

def solar(self, data: PathLike | TableLike | None = None, **kwargs) -> None:
    """
    Plot day-light terminators.
    
    Parameters:
    - data: Sun position data or datetime
    - region: Geographic extent
    - projection: Map projection
    - terminator: Terminator type (day/night/civil/nautical/astronomical)
    - pen: Pen attributes for terminator line
    - fill: Fill color for night areas
    """

Lines and Text

Functions for adding lines, text, and annotations to figures.

def hlines(self, y: float | list, **kwargs) -> None:
    """
    Plot horizontal lines.
    
    Parameters:
    - y: Y-coordinate(s) for horizontal lines
    - region: Plot extent
    - pen: Pen attributes for lines
    """

def vlines(self, x: float | list, **kwargs) -> None:
    """
    Plot vertical lines.
    
    Parameters:
    - x: X-coordinate(s) for vertical lines  
    - region: Plot extent
    - pen: Pen attributes for lines
    """

def text(self, textfiles: PathLike | TableLike | None = None, x=None, y=None,
          position: Literal["TL", "TC", "TR", "ML", "MC", "MR", "BL", "BC", "BR"] | None = None,
          **kwargs) -> None:
    """
    Plot or typeset text strings.
    
    Parameters:
    - textfiles: Text data file or table
    - x, y: Text position coordinates
    - position: Text anchor position
    - region: Geographic extent
    - projection: Map projection
    - font: Font specification
    - justify: Text justification
    - angle: Text rotation angle
    - fill: Text box fill color
    - pen: Text box outline
    """

Figure Elements

Functions for adding colorbars, legends, logos, and other figure elements.

def colorbar(self, **kwargs) -> None:
    """
    Plot colorbars on maps.
    
    Parameters:
    - position: Colorbar position and size
    - cmap: Color palette file
    - frame: Colorbar frame and annotations
    - scale: Value scaling
    - box: Colorbar background box
    """

def legend(self, spec: PathLike | list | None = None, **kwargs) -> None:
    """
    Plot a legend.
    
    Parameters:
    - spec: Legend specification file or list
    - position: Legend position
    - box: Legend background box
    - spacing: Line spacing
    """

def logo(self, **kwargs) -> None:
    """
    Place the GMT logo on a plot.
    
    Parameters:
    - position: Logo position
    - julia: Plot Julia logo instead of GMT
    """

def timestamp(self, **kwargs) -> None:
    """
    Plot time stamps on maps.
    
    Parameters:
    - position: Timestamp position
    - format: Time format string
    - font: Font specification
    """

Layout and Subplots

Functions for managing figure layout and creating multi-panel plots.

def inset(self, **kwargs) -> None:
    """
    Create and manage figure insets.
    
    Parameters:
    - position: Inset position and size
    - box: Inset border
    - margin: Inset margins
    - translate: Coordinate translation
    """

def subplot(self, nrows: int = 1, ncols: int = 1, **kwargs) -> None:
    """
    Create multi-panel subplot figures.
    
    Parameters:
    - nrows: Number of subplot rows
    - ncols: Number of subplot columns
    - figsize: Overall figure size
    - frame: Subplot frame configuration
    - margins: Subplot margins and spacing
    - title: Overall figure title
    """

def set_panel(self, panel=None, **kwargs) -> None:
    """
    Activate a specific subplot panel.
    
    Parameters:
    - panel: Panel identifier (row, col) or index
    - fixedlabel: Set fixed subplot labels
    """

Utility Functions

Figure utility functions for coordinate transformation and output processing.

def shift_origin(self, xshift: str | None = None, yshift: str | None = None, 
                 **kwargs) -> None:
    """
    Shift plot origin in x and/or y directions.
    
    Parameters:
    - xshift: X-direction shift amount (with units)
    - yshift: Y-direction shift amount (with units)
    """

def psconvert(self, **kwargs) -> None:
    """
    Convert PostScript to other formats using Ghostscript.
    
    Parameters:
    - format: Output format (jpg/png/pdf/eps/tif/etc.)
    - prefix: Output file prefix
    - dpi: Output resolution
    - crop: Crop to bounding box
    - background: Background color
    """

def tilemap(self, region: str | list, **kwargs) -> None:
    """
    Plot web map tiles as a basemap or overlay.
    
    Parameters:
    - region: Geographic extent for tiles
    - projection: Map projection
    - source: Tile source (OpenStreetMap/ESRI/etc.)
    - zoom: Zoom level
    - alpha: Tile transparency
    """

Usage Examples

Basic Map Creation

import pygmt

# Create figure and basic map
fig = pygmt.Figure()
fig.basemap(region="global", projection="W15c", frame="a30f15")
fig.coast(shorelines=True, land="tan", water="lightblue")
fig.show()

Data Plotting with Grid

import pygmt

# Load sample grid data
grid = pygmt.datasets.load_earth_relief(resolution="05m", region=[-180, 180, -60, 60])

# Plot the grid
fig = pygmt.Figure()
fig.grdimage(grid=grid, projection="W15c", cmap="geo", frame=True)
fig.coast(shorelines=True)
fig.colorbar(frame='a2000+l"Elevation (m)"')
fig.show()

Multi-Panel Figure

import pygmt
import numpy as np

# Create subplot figure
fig = pygmt.Figure()
fig.subplot(nrows=2, ncols=2, figsize="15c", frame="WSen")

# Panel 1
fig.set_panel(panel=0)
fig.basemap(region="global", projection="W?", frame="a60f30")
fig.coast(land="gray")

# Panel 2  
fig.set_panel(panel=1)
x = np.arange(0, 10, 0.1)
y = np.sin(x)
fig.plot(x=x, y=y, region=[0, 10, -1.5, 1.5], projection="X?/5c", 
         pen="2p,blue", frame="ag")

fig.show()

Install with Tessl CLI

npx tessl i tessl/pypi-pygmt

docs

config-utilities.md

data-processing.md

datasets.md

figure-plotting.md

index.md

tile.json