API Reference

PyGMT is a library for processing geospatial and geophysical data and making publication quality maps and figures. It provides a Pythonic interface for the Generic Mapping Tools (GMT), a command-line program widely used in the Earth Sciences. Besides making GMT more accessible to new users, PyGMT aims to provide integration with the PyData ecosystem as well as support for rich display in Jupyter notebooks.

Main Features

Here are just a few of the things that PyGMT does well:

  • Easy handling of individual types of data like Cartesian, geographic, or time-series data.

  • Processing of (geo)spatial data including gridding, filtering, and masking.

  • Allows plotting of a large spectrum of objects on figures including lines, vectors, polygons, and symbols (pre-defined and customized).

  • Generate publication-quality illustrations and make animations.

Plotting

Figure class overview

All plotting is handled through the pygmt.Figure class and its methods.

Figure()

A GMT figure to handle all plotting.

Plotting map elements

Figure.basemap(*[, region, projection, ...])

Plot base maps and frames for the figure.

Figure.coast(*[, region, projection, ...])

Plot continents, shorelines, rivers, and borders on maps.

Figure.colorbar(*[, region, projection, ...])

Plot a gray or color scale-bar on maps.

Figure.inset(*[, position, box, projection, ...])

Create an inset figure to be placed within a larger figure.

Figure.legend([spec, position, box, region, ...])

Plot legends on maps.

Figure.logo(*[, region, projection, ...])

Plot the GMT logo.

Figure.solar([terminator, ...])

Plot day-light terminators or twilights.

Figure.text([textfiles, x, y, position, ...])

Plot or typeset text strings of variable size, font type, and orientation.

Plotting tabular data

Figure.contour([data, x, y, z, annotation, ...])

Contour table data by direct triangulation.

Figure.histogram(data, *[, horizontal, ...])

Plots a histogram, and can read data from a file or list, array, or dataframe.

Figure.meca(spec, scale[, convention, ...])

Plot focal mechanisms.

Figure.plot([data, x, y, size, direction, ...])

Plot lines, polygons, and symbols in 2-D.

Figure.plot3d([data, x, y, z, size, ...])

Plot lines, polygons, and symbols in 3-D.

Figure.rose([data, length, azimuth, sector, ...])

Plot windrose diagrams or polar histograms.

Figure.ternary(data[, alabel, blabel, ...])

Reads (a,b,c[,z]) records from data and plots symbols at those locations on a ternary diagram.

Figure.velo([data, vector, frame, cmap, ...])

Plot velocity vectors, crosses, anisotropy bars, and wedges.

Figure.wiggle([data, x, y, z, frame, ...])

Plot z=f(x,y) anomalies along tracks.

Plotting raster data

Figure.grdcontour(grid, *[, annotation, ...])

Convert grids or images to contours and plot them on maps.

Figure.grdimage(grid, *[, img_out, frame, ...])

Project and plot grids or images.

Figure.grdview(grid, *[, region, ...])

Create 3-D perspective image or surface mesh from a grid.

Figure.image(imagefile, *[, region, ...])

Place images or EPS files on maps.

Configuring layout

Figure.set_panel([panel, fixedlabel, ...])

Set the current subplot panel to plot on.

Figure.shift_origin([xshift, yshift])

Shift plot origin in x and/or y directions.

Figure.subplot([nrows, ncols, figsize, ...])

Create multi-panel subplot figures.

Saving and displaying the figure

Figure.savefig(fname[, transparent, crop, ...])

Save the figure to a file.

Figure.show([dpi, width, method, waiting])

Display a preview of the figure.

Figure.psconvert([icc_gray, crop, ...])

Convert [E]PS file(s) to other formats.

Configuring the display settings

The following function is provided directly through the pygmt top level package.

set_display([method])

Set the display method.

Color palette table generation

The following functions are provided directly through the pygmt top level package.

grd2cpt(grid, *[, transparency, cmap, ...])

Make GMT color palette tables from a grid file.

makecpt(*[, transparency, cmap, background, ...])

Make GMT color palette tables.

Data Processing

Operations on tabular data

binstats(data, *[, statistic, empty, ...])

Bin spatial data and determine statistics per bin.

blockmean([data, x, y, z, outfile, spacing, ...])

Block average (x,y,z) data tables by mean estimation.

blockmedian([data, x, y, z, outfile, ...])

Block average (x,y,z) data tables by median estimation.

blockmode([data, x, y, z, outfile, spacing, ...])

Block average (x,y,z) data tables by mode estimation.

filter1d(data[, output_type, outfile, end, ...])

Time domain filtering of 1-D data tables.

nearneighbor([data, x, y, z, empty, ...])

Grid table data using a "Nearest neighbor" algorithm.

project([data, x, y, z, outfile, azimuth, ...])

Project data onto lines or great circles, or generate tracks.

select([data, outfile, area_thresh, ...])

Select data table subsets based on multiple spatial criteria.

sph2grd(data, *[, outgrid, spacing, region, ...])

Create spherical grid files in tension of data.

sphdistance([data, x, y, single_form, ...])

Create Voronoi distance, node, or natural nearest-neighbor grid on a sphere.

sphinterpolate(data, *[, outgrid, spacing, ...])

Create spherical grid files in tension of data.

surface([data, x, y, z, spacing, region, ...])

Grids table data using adjustable tension continuous curvature splines.

triangulate()

Delaunay triangulation or Voronoi partitioning and gridding of Cartesian data.

triangulate.regular_grid([data, x, y, z, ...])

Delaunay triangle based gridding of Cartesian data.

triangulate.delaunay_triples([data, x, y, ...])

Delaunay triangle based gridding of Cartesian data.

xyz2grd([data, x, y, z, duplicate, outgrid, ...])

Create a grid file from table data.

Operations on raster data

dimfilter(grid, *[, distance, filter, ...])

Filter a grid by dividing the filter circle.

grd2xyz(grid[, output_type, outfile, ...])

Convert grid to data table.

grdclip(grid, *[, outgrid, region, above, ...])

Sets values in a grid that meet certain criteria to a new value.

grdcut(grid, *[, outgrid, region, ...])

Extract subregion from a grid.

grdfill(grid, *[, mode, outgrid, region, ...])

Fill blank areas from a grid file.

grdfilter(grid, *[, distance, filter, ...])

Filter a grid in the space (or time) domain.

grdgradient(grid, *[, azimuth, direction, ...])

Compute the directional derivative of the vector gradient of the data.

grdhisteq()

Perform histogram equalization for a grid.

grdhisteq.equalize_grid(grid, *[, outgrid, ...])

Perform histogram equalization for a grid.

grdhisteq.compute_bins(grid, *[, ...])

Perform histogram equalization for a grid.

grdlandmask(*[, area_thresh, resolution, ...])

Create a grid file with set values for land and water.

grdproject(grid, *[, center, spacing, dpi, ...])

Change projection of gridded data between geographical and rectangular.

grdsample(grid, *[, outgrid, spacing, ...])

Change the registration, spacing, or nodes in a grid file.

grdtrack(grid[, points, newcolname, ...])

Sample grids at specified (x,y) locations.

grdvolume(grid[, output_type, outfile, ...])

Determine the volume between the surface of a grid and a plane.

Crossover analysis with x2sys

x2sys_init(tag, *[, fmtfile, suffix, force, ...])

Initialize a new x2sys track database.

x2sys_cross([tracks, outfile, combitable, ...])

Calculate crossovers between track data files.

Input/output

load_dataarray(filename_or_obj, **kwargs)

Open, load into memory, and close a DataArray from a file or file-like object containing a single data variable.

GMT Defaults

Operations on GMT defaults:

config(**kwargs)

Set GMT defaults globally or locally.

Metadata

Getting metadata from tabular or grid data:

GMTDataArrayAccessor(xarray_obj)

This is the GMT extension for xarray.DataArray.

info(data, *[, per_column, spacing, ...])

Get information about data tables.

grdinfo(grid, *[, per_column, tiles, ...])

Get information about a grid.

Miscellaneous

which(fname, *[, download, verbose])

Find the full path to specified files.

test([doctest, verbose, coverage, figures])

Run the test suite.

print_clib_info()

Print information about the GMT shared library that we can find.

show_versions()

Prints various dependency versions useful when submitting bug reports.

Datasets

PyGMT provides access to GMT’s datasets through the pygmt.datasets package. These functions will download the datasets automatically the first time they are used and store them in the GMT cache folder.

datasets.list_sample_data()

Report datasets available for tests and documentation examples.

datasets.load_earth_age([resolution, ...])

Load Earth seafloor crustal ages in various resolutions.

datasets.load_earth_relief([resolution, ...])

Load Earth relief grids (topography and bathymetry) in various resolutions.

datasets.load_sample_data(name)

Load an example dataset from the GMT server.

datasets.load_fractures_compilation(**kwargs)

(Deprecated) Load a table of fracture lengths and azimuths as hypothetically digitized from geological maps as a pandas.DataFrame.

datasets.load_hotspots(**kwargs)

(Deprecated) Load a table with the locations, names, and suggested symbol sizes of hotspots.

datasets.load_japan_quakes(**kwargs)

(Deprecated) Load a table of earthquakes around Japan as a pandas.DataFrame.

datasets.load_mars_shape(**kwargs)

(Deprecated) Load a table of data for the shape of Mars.

datasets.load_ocean_ridge_points(**kwargs)

(Deprecated) Load a table of ocean ridge points for the entire world as a pandas.DataFrame.

datasets.load_sample_bathymetry(**kwargs)

(Deprecated) Load a table of ship observations of bathymetry off Baja California as a pandas.DataFrame.

datasets.load_usgs_quakes(**kwargs)

(Deprecated) Load a table of global earthquakes from the USGS as a pandas.DataFrame.

Exceptions

All custom exceptions are derived from pygmt.exceptions.GMTError.

exceptions.GMTError

Base class for all GMT related errors.

exceptions.GMTInvalidInput

Raised when the input of a function/method is invalid.

exceptions.GMTVersionError

Raised when an incompatible version of GMT is being used.

exceptions.GMTOSError

Unsupported operating system.

exceptions.GMTCLibError

Error encountered when running a function from the GMT shared library.

exceptions.GMTCLibNoSessionError

Tried to access GMT API without a currently open GMT session.

exceptions.GMTCLibNotFoundError

Could not find the GMT shared library.

GMT C API

The pygmt.clib package is a wrapper for the GMT C API built using ctypes. Most calls to the C API happen through the pygmt.clib.Session class.

clib.Session()

A GMT API session where most operations involving the C API happen.

GMT modules are executed through the call_module method:

clib.Session.call_module(module, args)

Call a GMT module with the given arguments.

Passing memory blocks between Python data objects (e.g. numpy.ndarray, pandas.Series, xarray.DataArray, etc) and GMT happens through virtual files. These methods are context managers that automate the conversion of Python variables to GMT virtual files:

clib.Session.virtualfile_from_data([...])

Store any data inside a virtual file.

clib.Session.virtualfile_from_matrix(matrix)

Store a 2d array as a table inside a virtual file.

clib.Session.virtualfile_from_vectors(*vectors)

Store 1d arrays as columns of a table inside a virtual file.

clib.Session.virtualfile_from_grid(grid)

Store a grid in a virtual file.

Low level access (these are mostly used by the pygmt.clib package):

clib.Session.create(name)

Create a new GMT C API session.

clib.Session.destroy()

Destroy the currently open GMT API session.

clib.Session.__getitem__(name)

Get the value of a GMT constant (C enum) from gmt_resources.h.

clib.Session.__enter__()

Create a GMT API session and check the libgmt version.

clib.Session.__exit__(exc_type, exc_value, ...)

Destroy the currently open GMT API session.

clib.Session.get_default(name)

Get the value of a GMT default parameter (library version, paths, etc).

clib.Session.create_data(family, geometry, ...)

Create an empty GMT data container.

clib.Session.put_matrix(dataset, matrix[, pad])

Attach a numpy 2D array to a GMT dataset.

clib.Session.put_strings(dataset, family, ...)

Attach a numpy 1D array of dtype str as a column on a GMT dataset.

clib.Session.put_vector(dataset, column, vector)

Attach a numpy 1D array as a column on a GMT dataset.

clib.Session.write_data(family, geometry, ...)

Write a GMT data container to a file.

clib.Session.open_virtual_file(family, ...)

Open a GMT Virtual File to pass data to and from a module.

clib.Session.extract_region()

Extract the WESN bounding box of the currently active figure.

clib.Session.get_libgmt_func(name[, ...])

Get a ctypes function from the libgmt shared library.