Reference manual

The gmtpy module

A Python interface to GMT.

class GMT(config=None, kontinue=None, version='newest')[source]

A thin wrapper to GMT command execution.

A dict config may be given to override some of the default GMT parameters. The version argument may be used to select a specific GMT version, which should be used with this GMT instance. The selected version of GMT has to be installed on the system, must be supported by gmtpy and gmtpy must know where to find it.

Each instance of this class is used for the task of producing one PS or PDF output file.

Output of a series of GMT commands is accumulated in memory and can then be saved as PS or PDF file using the save() method.

GMT commands are accessed as method calls to instances of this class. See the __getattr__() method for details on how the method’s arguments are translated into options and arguments for the GMT command.

Associated with each instance of this class, a temporary directory is created, where temporary files may be created, and which is automatically deleted, when the object is destroyed. The tempfilename() method may be used to get a random filename in the instance’s temporary directory.

Any .gmtdefaults files are ignored. The GMT class uses a fixed set of defaults, which may be altered via an argument to the constructor. If possible, GMT is run in ‘isolation mode’, which was introduced with GMT version 4.2.2, by setting GMT_TMPDIR to the instance’s temporary directory. With earlier versions of GMT, problems may arise with parallel execution of more than one GMT instance.

Each instance of the GMT class may pick a specific version of GMT which shall be used, so that, if multiple versions of GMT are installed on the system, different versions of GMT can be used simultaneously such that backward compatibility of the scripts can be maintained.


Maps to call self._gmtcommand(command, *addargs, **kwargs).

Execute arbitrary GMT command.

Run a GMT command and by default append its postscript output to the output file maintained by the GMT instance on which this method is called.

Except for a few keyword arguments listed below, any kwargs and addargs are converted into command line options and arguments and passed to the GMT command. Numbers in keyword arguments are converted into strings. E.g. S=10 is translated into '-S10'. Tuples of numbers or strings are converted into strings where the elements of the tuples are separated by slashes ‘/’. E.g. R=(10,10,20,20) is translated into '-R10/10/20/20'. Options with a boolean argument are only appended to the GMT command, if their values are True.

If no output redirection is in effect, the -K and -O options are handled by gmtpy and thus should not be specified. Use out_discard=True if you don’t want -K or -O beeing added, but are not interested in the output.

The standard input of the GMT process is fed by data selected with one of the following in_* keyword arguments:

in_stream Data is read from an open file like object.
in_filename Data is read from the given file.
in_string String content is dumped to the process.
in_columns A 2D nested iterable whose elements can be accessed as in_columns[icolumn][irow] is converted into an ascii table, which is fed to the process.
in_rows A 2D nested iterable whos elements can be accessed as in_rows[irow][icolumn] is converted into an ascii table, which is fed to the process.

The standard output of the GMT process may be redirected by one of the following options:

out_stream Output is fed to an open file like object.
out_filename Output is dumped to the given file.
out_discard If True, output is dumped to /dev/null.

Additional keyword arguments:

config Dict with GMT defaults which override the currently active set of defaults exclusively during this call.
finish If True, the postscript file, which is maintained by the GMT instance is finished, and no further plotting is allowed.
suppress_defaults Suppress appending of the '+gmtdefaults' option to the command.

Get filename for temporary file in the private temp directory.

If no name argument is given, a random name is picked. If name is given, returns a path ending in that name.


Create and open a file in the private temp directory.

save(filename=None, bbox=None, raster_dpi=150, raster_antialias=True)[source]

Finish and save figure as PDF, PS or PPM file.

If filename ends with '.pdf' a PDF file is created by piping the GMT output through epstopdf.

If filename ends with '.ppm' a PPM file is created by running epstopdf and pdftoppm. raster_dpi specifies the resolution, which is passed to pdftoppm.

The bounding box is set according to the values given in bbox.


Get the command log.


Try to get paper size of output postscript file in points.


Get a default layout for the output page.

One of three different layouts is choosen, depending on the PAPER_MEDIA setting in the GMT configuration dict.

If PAPER_MEDIA ends with a '+' (EPS output is selected), a FrameLayout is centered on the page, whose size is controlled by its center widget’s size plus the margins of the FrameLayout.

If PAPER_MEDIA indicates, that a custom page size is wanted by starting with 'Custom_', a FrameLayout is used to fill the complete page. The center widget’s size is then controlled by the page’s size minus the margins of the FrameLayout.

In any other case, two FrameLayouts are nested, such that the outer layout attaches a 1 cm (printer) margin around the complete page, and the inner FrameLayout’s center widget takes up as much space as possible under the constraint, that an aspect ratio of 1/golden_ratio is preserved.

In any case, a reference to the innermost FrameLayout instance is returned. The top-level layout can be accessed by calling Widget.get_parent() on the returned layout.


Use psxy to draw layout; for debugging

class Guru[source]

Abstract base class providing template interpolation, accessible as attributes.

Classes deriving from this one, have to implement a get_params() method, which is called to get a dict to do ordinary "%(key)x"-substitutions. The deriving class must also provide a dict with the templates.

class AutoScaler(approx_ticks=7.0, mode='auto', exp=None, snap=False, inc=None, space=0.0, exp_factor=3, no_exp_interval=(-3, 5))[source]

Tunable 1D autoscaling based on data range.

Instances of this class may be used to determine nice minima, maxima and increments for ax annotations, as well as suitable common exponents for notation.

The autoscaling process is guided by the following public attributes:


Approximate number of increment steps (tickmarks) to generate.


Mode of operation: one of 'auto', 'min-max', '0-max', 'min-0', 'symmetric' or 'off'.

mode description
'auto': Look at data range and choose one of the choices below.
'min-max': Output range is selected to include data range.
'0-max': Output range shall start at zero and end at data max.
'min-0': Output range shall start at data min and end at zero.
'symmetric': Output range shall by symmetric by zero.
'off': Similar to 'min-max', but snap and space are disabled, such that the output range always exactly matches the data range.

If defined, override automatically determined exponent for notation by the given value.


If set to True, snap output range to multiples of increment. This parameter has no effect, if mode is set to 'off'.


If defined, override automatically determined tick increment by the given value.


Add some padding to the range. The value given, is the fraction by which the output range is increased on each side. If mode is '0-max' or 'min-0', the end at zero is kept fixed at zero. This parameter has no effect if mode is set to 'off'.


Exponent of notation is chosen to be a multiple of this value.


Range of exponent, for which no exponential notation is allowed.

make_scale(data_range, override_mode=None)[source]

Get nice minimum, maximum and increment for given data range.

Returns (minimum, maximum, increment) or (maximum, minimum, -increment), depending on whether data_range is (data_min, data_max) or (data_max, data_min). If override_mode is defined, the mode attribute is temporarily overridden by the given value.


Get nice exponent for notation of x.

For ax annotations, give tick increment as x.

guess_autoscale_mode(data_min, data_max)[source]

Guess mode of operation, based on data range.

Used to map 'auto' mode to '0-max', 'min-0', 'min-max' or 'symmetric'.

class Ax(label='', unit='', scaled_unit_factor=1.0, scaled_unit='', limits=None, masking=True, **kwargs)[source]

Ax description with autoscaling capabilities.

The ax is described by the AutoScaler public attributes, plus the following additional attributes (with default values given in paranthesis):


Ax label (without unit).


Physical unit of the data attached to this ax.


(see below)


Scaled physical unit and factor between unit and scaled_unit such that

unit = scaled_unit_factor x scaled_unit.

(E.g. if unit is ‘m’ and data is in the range of nanometers, you may want to set the scaled_unit to ‘nm’ and the scaled_unit_factor to 1e9.)


If defined, fix range of ax to limits=(min,max).


If true and if there is a limit on the ax, while calculating ranges, the data points are masked such that data points outside of this axes limits are not used to determine the range of another dependant ax.

label_str(exp, unit)[source]

Get label string including the unit and multiplier.

make_params(data_range, ax_projection=False, override_mode=None, override_scaled_unit_factor=None)[source]

Get minimum, maximum, increment and label string for ax display.’

Returns minimum, maximum, increment and label string including unit and multiplier for given data range.

If ax_projection is True, values suitable to be displayed on the ax are returned, e.g. min, max and inc are returned in scaled units. Otherwise the values are returned in the original units, without any scaling applied.

class ScaleGuru(data_tuples=None, axes=None, aspect=None, percent_interval=None)[source]

2D/3D autoscaling and ax annotation facility.

Instances of this class provide automatic determination of plot ranges, tick increments and scaled annotations, as well as label/unit handling. It can in particular be used to automatically generate the -R and -B option arguments, which are required for most GMT commands.

It extends the functionality of the Ax and AutoScaler classes at the level, where it can not be handled anymore by looking at a single dimension of the dataset’s data, e.g.:

  • The ability to impose a fixed aspect ratio between two axes.
  • Recalculation of data range on non-limited axes, when there are limits imposed on other axes.

Get dict with output parameters.

For each data dimension, ax minimum, maximum, increment and a label string (including unit and exponential factor) are determined. E.g. in for the first dimension the output dict will contain the keys 'xmin', 'xmax', 'xinc', and 'xlabel'.

Normally, values corresponding to the scaling of the raw data are produced, but if ax_projection is True, values which are suitable to be printed on the axes are returned. This means that in the latter case, the Ax.scaled_unit and Ax.scaled_unit_factor attributes as set on the axes are respected and that a common 10^x factor is factored out and put to the label string.

class Widget(horizontal=None, vertical=None, parent=None)[source]

Base class of the gmtpy layout system.

The Widget class provides the basic functionality for the nesting and placing of elements on the output page, and maintains the sizing policies of each element. Each of the layouts defined in gmtpy is itself a Widget.

Sizing of the widget is controlled by get_min_size() and get_grow() which should be overloaded in derived classes. The basic behaviour of a Widget instance is to have a vertical and a horizontal minimum size which default to zero, as well as a vertical and a horizontal desire to grow, represented by floats, which default to 1.0. Additionally an aspect ratio constraint may be imposed on the Widget.

After layouting, the widget provides its width, height, x-offset and y-offset in various ways. Via the Guru interface (see Guru class), templates for the -X, -Y and -J option arguments used by GMT arguments are provided. The defaults are suitable for plotting of linear (-JX) plots. Other projections can be selected by giving an appropriate ‘J’ template, or by manual construction of the -J option, e.g. by utilizing the width() and height() methods. The bbox() method can be used to create a PostScript bounding box from the widgets border, e.g. for use in the save() method of GMT instances.

The convention is, that all sizes are given in PostScript points. Conversion factors are provided as constants inch and cm in the gmtpy module.


Set the parent widget.

This method should not be called directly. The set_widget() methods are responsible for calling this.


Get the widgets parent widget.


Get the root widget in the layout hierarchy.

set_horizontal(minimal=None, grow=None)[source]

Set the horizontal sizing policy of the Widget.

  • minimal – new minimal width of the widget
  • grow – new horizontal grow disire of the widget
set_vertical(minimal=None, grow=None)[source]

Set the horizontal sizing policy of the Widget.

  • minimal – new minimal height of the widget
  • grow – new vertical grow disire of the widget

Set aspect constraint on the widget.

The aspect is given as height divided by width.

set_policy(minimal=(None, None), grow=(None, None), aspect=None)[source]

Shortcut to set sizing and aspect constraints in a single method call.

legalize(size, offset)[source]

Get legal size for widget.

Returns: (new_size, new_offset)

Given a box as size and offset, return new_size and new_offset, such that the widget’s sizing and aspect constraints are fullfilled. The returned box is centered on the given input box.


Get minimum size of widget.

Used by the layout managers. Should be overloaded in derived classes.


Get widget’s desire to grow.

Used by the layout managers. Should be overloaded in derived classes.

set_size(size, offset)[source]

Set the widget’s current size.

Should not be called directly. It is the layout manager’s responsibility to call this.


Get coordinates of the corners of the widget.

Returns list with coordinate tuples.

If descend is True, the returned list will contain corner coordinates of all sub-widgets.


Get sizes of this widget and all it’s children.

Returns a list with size tuples.


Triggers layouting of the widget hierarchy, if needed.


Get sub-widgets contained in this widget.

Returns a list of widgets.


Get current size and position of the widget.

Triggers layouting and returns ((width, height), (xoffset, yoffset))


Get current size and position of the widget.

Triggers layouting and returns dict with keys 'xoffset', 'yoffset', 'width' and 'height'.


Get current width of the widget.

Triggers layouting and returns width.


Get current height of the widget.

Triggers layouting and return height.


Get PostScript bounding box for this widget.

Triggers layouting and returns values suitable to create PS bounding box, representing the widgets current size and position.


Set dirty flag on top level widget in the hierarchy.

Called by various methods, to indicate, that the widget hierarchy needs new layouting.

class CenterLayout(horizontal=None, vertical=None)[source]

A layout manager which centers its single child widget.

The child widget may be oversized.


Set the child widget, which shall be centered.

class FrameLayout(horizontal=None, vertical=None)[source]

A layout manager containing a center widget sorrounded by four margin widgets.

|             top           |
|      |            |       |
| left |   center   | right |
|      |            |       |
|           bottom          |

This layout manager does a little bit of extra effort to maintain the aspect constraint of the center widget, if this is set. It does so, by allowing for a bit more flexibility in the sizing of the margins. Two shortcut methods are provided to set the margin sizes in one shot: set_fixed_margins() and set_min_margins(). The first sets the margins to fixed sizes, while the second gives them a minimal size and a (neglectably) small desire to grow. Using the latter may be useful when setting an aspect constraint on the center widget, because this way the maximum size of the center widget may be controlled without creating empty spaces between the widgets.

set_fixed_margins(left, right, top, bottom)[source]

Give margins fixed size constraints.

set_min_margins(left, right, top, bottom, grow=0.0001)[source]

Give margins a minimal size and the possibility to grow.

The desire to grow is set to a very small number.

set_widget(which='center', widget=None)[source]

Set one of the sub-widgets.

which should be one of 'left', 'right', 'top', 'bottom' or 'center'.


Get one of the sub-widgets.

which should be one of 'left', 'right', 'top', 'bottom' or 'center'.

class GridLayout(nx=2, ny=2, horizontal=None, vertical=None)[source]

A layout manager which arranges its sub-widgets in a grid.

The grid spacing is flexible and based on the sizing policies of the contained sub-widgets. If an equidistant grid is needed, the sizing policies of the sub-widgets have to be set equally.

The height of each row and the width of each column is derived from the sizing policy of the largest sub-widget in the row or column in question. The algorithm is not very sophisticated, so conflicting sizing policies might not be resolved optimally.

set_widget(ix, iy, widget=None)[source]

Set one of the sub-widgets.

Sets the sub-widget in column ix and row iy. The indices are counted from zero.

get_widget(ix, iy)[source]

Get one of the sub-widgets.

Gets the sub-widget from column ix and row iy. The indices are counted from zero.


Generate a string for GMT option arguments expecting a color.

If x is None, a random color is returned. If it is an integer, the corresponding gmtpy.graph_colors[x] or black returned. If it is a string and the corresponding gmtpy.tango_colors[x] exists, this is returned, or the string is passed through. If x is a tuple, it is transformed into the string form which GMT expects.


Read COARDS compliant netcdf (grd) file.

savegrd(x, y, z, filename, title=None, naming='xy')[source]

Write COARDS compliant netcdf (grd) file.