0% found this document useful (0 votes)
5 views

GMT tutorial

The document provides a comprehensive overview of the Generic Mapping Tools (GMT) system, detailing its historical development, philosophy, installation considerations, and usage. It outlines the structure of the GMT environment, including input and output data types, job control, and UNIX environment basics such as redirection and piping. Additionally, it includes tutorials on creating various types of plots using different projections, along with exercises to reinforce learning.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

GMT tutorial

The document provides a comprehensive overview of the Generic Mapping Tools (GMT) system, detailing its historical development, philosophy, installation considerations, and usage. It outlines the structure of the GMT environment, including input and output data types, job control, and UNIX environment basics such as redirection and piping. Additionally, it includes tutorials on creating various types of plots using different projections, along with exercises to reinforce learning.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 146

Introduction

Historical highlights

The GMT system was initiated in late 1987 at Lamont-Doherty Earth Observatory, Columbia University
by graduate students Paul Wessel and Walter H. F. Smith. Version 1 was officially introduced to Lamont
scientists in July 1988. GMT 1 migrated by word of mouth (and tape) to other institutions in the United
States, UK, Japan, and France and attracted a small following. Paul took a Post-doctoral position at
SOEST in December 1989 and continued the GMT development. Version 2.0 was released with an article
in EOS, October 1991, and quickly spread worldwide. Version 3.0 in 1993 which was released with
another article in EOS on August 15, 1995. A major upgrade to GMT 4.0 took place in Oct 2004. Finally,
in 2013 we released the new GMT 5 series and we have updated this tutorial to reflect the changes in
style and syntax. However, GMT 5 is generally backwards compatible with GMT 4 syntax. In October
2019 we released the current version GMT 6. GMT is used by tens of thousands of users worldwide in a
broad range of disciplines.

Philosophy

GMT follows the UNIX philosophy in which complex tasks are broken down into smaller and more
manageable components. Individual GMT modules are small, easy to maintain, and can be used as any
other UNIX tool. GMT is written in the ANSI C programming language (very portable), is POSIX compliant,
and is independent of hardware constraints (e.g., memory). GMT was deliberately written for command-
line usage, not a windows environment, in order to maximize flexibility. We standardized early on to use
PostScript output instead of other graphics formats. Apart from the built-in support for coastlines, GMT
completely decouples data retrieval from the main GMT modules. GMT uses architecture-independent
file formats.

GMT installation considerations

See the install guide for instructions and to make sure you have all required dependencies installed.
Alternatively, you can build GMT from source by following the building guide.

In addition, we recommend access to any flavor of the UNIX operating system (UNIX, Linux, macOS,
Cygwin, MinGW, etc.). We do not recommend using the DOS command window under Windows.
Session One
Tutorial setup
1. We assume that GMT has been properly and fully installed and that the GMT
executables are in your executable path. You should be able to type gmt in your
terminal and it will display the GMT splash screen with version number and the top-
level options. If not then you need to work on your user environment, adding the
path to the gmt executable to your search path.
2. All GMT man pages, documentation, and gallery example scripts are available from
the GMT documentation web page. It is assumed these pages have been installed
locally at your site; if not they are always available from https://docs.generic-
mapping-tools.org.
3. We recommend you create a sub-directory called tutorial, cd into that directory, and
run the commands there to keep things tidy.
4. As we discuss GMT principles it may be a good idea to consult the GMT
Cookbook for more detailed explanations.
5. The tutorial data sets are distributed via the GMT cache server. You will therefore
find that all the data files have a “@” prepended to their names. This will ensure the
file is copied from the server before being used, hence you do not need to download
any of the data manually. The only downside is that you will need an Internet
connection to run the examples by cut and paste.
6. For all but the simplest GMT jobs it is recommended that you place all the GMT (and
UNIX) commands in a shell script file and make it executable. To ensure that UNIX
recognizes your script as a shell script it is a good habit always to start the script
with the line #!/usr/bin/env bash or #!/usr/bin/env csh , depending on the shell you
prefer to use. All the examples in this tutorial assumes you are running the Bourne
Again shell, bash, and you will need to modify some of the constructs, such as i/o
redirection, to run these examples under csh. We strongly recommend bash over
csh due the ability to define functions.
7. Making a script executable is accomplished using the chmod command, e.g., the
script figure_1.sh is made executable with “chmod +x figure_1.sh”.
8. Please cd into the directory tutorial. We are now ready to start.
The GMT environment: What happens when you
run GMT ?
To get a good grasp on GMT one must understand what is going on “under the hood”.
The GMT Run-Time Environment illustrates the relationships you need to be aware of at
run-time.

The GMT run-time environment. The session will initiate with a set of system defaults
that you can override with having your own gmt.conf file in the current directory,
specifying GMT parameters via the --PAR=value technique, and supply module
options. Some GMT modules will read hidden data (like coastlines) but most will
explicitly need to be given user data.
Input data

A GMT module may or may not take input files. Three different types of input are
recognized (more details can be found in GMT File Formats):

1. Data tables. These are rectangular tables with a fixed number of columns and
unlimited number of rows. We distinguish between two groups:
 ASCII (Preferred unless files are huge)
 Binary (to speed up input/output)

Such tables may have segment headers and can therefore hold any number of
subsets such as individual line segments or polygons.

2. Gridded dated sets. These are data matrices (evenly spaced in two coordinates) that
come in two flavors:
 Grid-line registration
 Pixel registration
You may choose among several file formats (even define your own format), but the
GMT default is the architecture-independent netCDF format.

3. Color palette table (For imaging, color plots, and contour maps). We will discuss
these later.
Job Control

GMT modules may get operational parameters from several places:

1. Supplied command line options/switches or module defaults.


2. Short-hand notation to select previously used option arguments (stored in
gmt.history).
3. Implicitly using GMT defaults for a variety of parameters (stored in gmt.conf).
4. May use hidden support data like coastlines or PostScript patterns.
Output data

There are 6 general categories of output produced by GMT:

1. PostScript plot commands.


2. Data Table(s).
3. Gridded data set(s).
4. Statistics & Summaries.
5. Warnings and Errors, written to stderr.
6. Exit status (0 means success, otherwise failure).
Note: GMT automatically creates and updates a history of past GMT command options
for the common switches. This history file is called gmt.history and one will be created in
every directory from which GMT modules are executed. Many initial problems with GMT
usage result from not fully appreciating the relationships shown in Figure GMT
Environment .

The UNIX Environment: Entry Level Knowledge


Redirection

Most GMT modules read their input from the terminal (called stdin) or from files, and
write their output to the terminal (called stdout). To use files instead one can use
redirection:
gmt module input-file > output-file # Read a file and redirect output
gmt module < input-file > output-file # Redirect input and output
gmt module input-file >> output-file # Append output to existing file

In this example, and in all those to follow, it is assumed that you do not have the shell
variable noclobber set. If you do, it prevents accidental overwriting of existing files.
That may be a noble cause, but it is extremely annoying. So please, unset noclobber.

Piping (|)

Sometimes we want to use the output from one module as input to another module.
This is achieved with pipes:

Someprogram | gmt module1 | gmt module1 > OutputFile

Standard error (stderr)

Most programs and GMT modules will on occasion write error messages. These are
typically written to a separate data stream called stderr and can be redirected
separately from the standard output (which goes to stdout). To send the error messages
to the same location as standard output we use:

program > errors.log 2>&1

When we want to save both program output and error messages to separate files we
use the following syntax:

gmt module > output.txt 2> errors.log

File name expansion or “wild cards”

UNIX provides several ways to select groups of files based on name patterns:
Code Meaning

* Matches anything

? Matches any single character

list Matches characters in the list

rang Matches characters in the given


e range

You can save much time by getting into the habit of selecting “good” filenames that
make it easy to select subsets of all files using the UNIX wild card notation.

Examples:

1. gmt module data_*.txt operates on all files starting with “data_” and ending in “.txt”.
2. gmt module line_?.txt works on all files starting with “line_” followed by any single
character and ending in “.txt”.
3. gmt module section_1[0-9]0.part_[12] only processes data from sections 100
through 190, only using every 10th profile, and gets both part 1 and 2.
Laboratory Exercises
We will begin our adventure by making some simple plot axes and coastline basemaps.
We will do this in order to introduce the all-important common options -B, -J, and -R and
to familiarize ourselves with a few selected GMT projections. The GMT modules we will
utilize are basemap and coast. Please consult their manual pages for reference.

Linear projection

We start by making the basemap frame for a linear x-y plot. We want it to go from 10 to
70 in x and from -3 to 8 in y, with automatic annotation intervals. Finally, we let the
canvas be painted light red and have dimensions of 4 by 3 inches. Here’s how we do it:

gmt begin GMT_tut_1


gmt set GMT_THEME cookbook
gmt basemap -R10/70/-3/8 -JX4i/3i -B -B+glightred+t"My first plot"
gmt end show
This script will open the result GMT_tut_1.pdf in a PDF viewer and it should look like our
example 1 below. Examine the basemap documentation so you understand what each
option means.

Result of GMT Tutorial example 1.


Exercises:

1. Try change the -JX values.


2. Try change the -B values.
3. Change title and canvas color.
Logarithmic projection
We next will show how to do a basemap for a log–log plot. We have no data set yet but
we will imagine that the raw x data range from 3 to 9613 and that y ranges from 10^20
to 10^24. One possibility is

gmt begin GMT_tut_2


gmt set GMT_THEME cookbook
gmt basemap -R1/10000/1e20/1e25 -JX9il/6il -Bxa2+l"Wavelength (m)" -
Bya1pf3+l"Power (W)" -BWS
gmt end show

Make sure your plot looks like our example 2 below

Result of GMT Tutorial example 2.


Exercises:

1. Do not append l to the axes lengths.


2. Leave the p modifier out of the -B string.
3. Add g3 to -Bx and -By.
Mercator projection

Despite the problems of extreme horizontal exaggeration at high latitudes, the


conformal Mercator projection (-JM) remains the stalwart of location maps used by
scientists. It is one of several cylindrical projections offered by GMT; here we will only
have time to focus on one such projection. The complete syntax is simply

-JMwidth
To make coastline maps we use coast which automatically will access the GMT
coastline, river and border data base derived from the GSHHG database [See Wessel
and Smith, 1996]. In addition to the common switches we may need to use some of
several coast-specific options:

Option Purpose

Exclude small features or those of high hierarchical levels


-A
(see GSHHG)

-D Select data resolution (full, high, intermediate, low, or crude)

-G Set color of dry areas (default does not paint)

-I Draw rivers (chose features from one or more hierarchical categories)

-L Plot map scale (length scale can be km, miles, or nautical miles)

-N Draw political borders (including US state borders)

-S Set color for wet areas (default does not paint)

-W Draw coastlines and set pen thickness

One of -W, -G, -S must be selected. Our first coastline example is from Latin America:

gmt begin GMT_tut_3


gmt set GMT_THEME cookbook
gmt coast -R-90/-70/0/20 -JM6i -B -Gchocolate
gmt end show

Your plot should look like our example 3 below


Result of GMT Tutorial example 3.
Exercises:

1. Add the -V option.


2. Try -R270/290/0/20 instead. What happens to the annotations?
3. Edit your gmt.conf file, change FORMAT_GEO_MAP to another setting (see
the gmt.conf documentation), and plot again.
4. Pick another region and change land color.
5. Pick a region that includes the north or south poles.
6. Try -W0.25p instead of (or in addition to) -G.
Albers projection

The Albers projection (-JB) is an equal-area conical projection; its conformal cousin is
the Lambert conic projection (-JL). Their usages are almost identical so we will only use
the Albers here. The general syntax is
-JBlon_0/lat_0/lat_1/lat_2/width

where (lon_0, lat_0) is the map (projection) center and lat_1, lat_2 are the two standard
parallels where the cone intersects the Earth’s surface. We try the following command:

gmt begin GMT_tut_4


gmt set GMT_THEME cookbook
gmt coast -R-130/-70/24/52 -JB-100/35/33/45/6i -B -B+t"Conic Projection" -
N1/thicker -N2/thinnest -A500 -Ggray -Wthinnest
gmt end show

Your plot should look like our example 4 below

Result of GMT Tutorial example 4.


Exercises:
1. Change the parameter MAP_GRID_CROSS_SIZE_PRIMARY to make grid crosses
instead of gridlines.
2. Change -R to a rectangular box specification instead of minimum and maximum
values.
Orthographic projection

The azimuthal orthographic projection (-JG) is one of several projections with similar
syntax and behavior; the one we have chosen mimics viewing the Earth from space at
an infinite distance; it is neither conformal nor equal-area. The syntax for this projection
is

-JGlon_0/lat_0/width

where (lon_0, lat_0) is the center of the map (projection). As an example we will try

gmt begin GMT_tut_5


gmt set GMT_THEME cookbook
gmt coast -Rg -JG280/30/6i -Bag -Dc -A5000 -Gwhite -SDarkTurquoise
gmt end show

Your plot should look like our example 5 below


Result of GMT Tutorial example 5
Exercises:

1. Use the rectangular option in -R to make a rectangular map showing the US only.
Eckert IV and VI projection

We conclude the survey of map projections with the Eckert IV and VI projections (-JK),
two of several projections used for global thematic maps; They are both equal-area
projections whose syntax is

-JK[f|s]lon_0/width

where f gives Eckert IV (4) and s (Default) gives Eckert VI (6). The lon_0 is the central
meridian (which takes precedence over the mid-value implied by the -R setting). A
simple Eckert VI world map is thus generated by

gmt begin GMT_tut_6


gmt set GMT_THEME cookbook
gmt coast -Rg -JKs180/9i -Bag -Dc -A5000 -Gchocolate -SDarkTurquoise -
Wthinnest
gmt end show

Your plot should look like our example 6 below

Result of GMT Tutorial example 6


Exercises:

1. Center the map on Greenwich.


2. Add a map scale with -L.

Session Two
General Information
There are 18 GMT modules that directly create (or add overlays to) plots; the remaining
45 are mostly concerned with data processing. This session will focus on the task of
plotting lines, symbols, and text on maps. We will build on the skills we acquired while
familiarizing ourselves with the various GMT map projections as well as how to select a
data domain and boundary annotations.
Program Purpose

BASEMAPS

basemap Create an empty basemap frame with optional scale

coast Plot coastlines, filled continents, rivers, and political borders

legend Create legend overlay

POINTS AND
LINES

wiggle Draw spatial time-series along their (x,y)-tracks

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

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

HISTOGRAMS

histogram Plot a rectangular histogram

rose Plot a polar histogram(sector/rose diagram)

CONTOURS

grdcontour Contouring of grids

contour Direct contouring/imaging of (x,y,z) data by optimal triangulation

SURFACES

grdimage Project and plot grids or images

grdvector Plot vector fields from grids

grdview 3-D perspective imaging of grids

UTILITIES

clip Use polygon files to initiate custom clipping paths

image Plot Sun raster files

mask Create clipping paths or generate overlay to mask

colorbar Plot gray scale or color scale bar


Program Purpose

text Plot text strings

Plotting lines and symbols, plot is one of the most frequently used modules in GMT. In
addition to the common command line switches it has numerous specific options, and
expects different file formats depending on what action has been selected. These
circumstances make plot harder to master than most GMT tools. The table below shows
an abbreviated list of the options:

Option Purpose

-A Suppress line interpolation along great circles

Let symbol color be determined from z-values and


-Ccpt
the cpt file

-E[x|X][y|Y][+wcap]
Draw selected error bars with specified attributes
[+ppen]

-Gfill Set color for symbol or fill for polygons

-L[options] Explicitly close polygons or create polygon (see plot)

-N[c|r] Do Not clip symbols at map borders

-S[symbol][size] Select one of several symbols

-Wpen Set pen for line or symbol outline

The symbols can either be transparent (using -W only, not -G) or solid (-G, with optional
outline using -W). The -S option takes the code for the desired symbol and optional size
information. If no symbol is given it is expected to be given in the last column of each
record in the input file. The size is optional since individual sizes for symbols may also
be provided by the input data. The main symbols available to us are shown in the table
below:

Option Symbol

-S-size horizontal dash; size is length of dash

-Sasize star; size is radius of circumscribing circle


Option Symbol

-Sbsize[/base]
bar; size is bar width, set unit be u if size is in x-units
[unit]

Bar extends from base [0] to the y-value

-Scsize circle; size is the diameter

-Sdsize diamond; size is its side

-Se ellipse; direction (CCW from horizontal), major, and minor axes

are read from the input file

ellipse; azimuth (CW from vertical), major, and minor axes in


-SE
kilometers

are read from the input file

-Sgsize octagon; size is its side

-Shsize hexagon; size is its side

-Sisize inverted triangle; size is its side

-Sksymbol/size kustom symbol; size is its side

-Slsize+tstring letter; size is fontsize. The string can be a letter or a text string

Append +ffont to set font and +jjust for justification

-Snsize pentagon; size is its side

-Sp point; no size needed (1 pixel at current resolution is used)

-Srsize rect, width and height are read from input file

-Sssize square, size is its side

-Stsize triangle; size is its side

vector; direction (CCW from horizontal) and length are read from input
-Svparams
data

Append parameters of the vector; see plot for syntax.

-SVparams vector, except azimuth (degrees east of north) is expected instead


Option Symbol

of direction

The angle on the map is calculated based on the chosen map projection

pie wedge; start and stop directions (CCW from horizontal) are read
-Sw[size]
from

input data

-Sxsize cross; size is length of crossing lines

-Sysize vertical dash; size is length of dash

The symbol option in plot. Lower case symbols (a, c, d, g, h, i, n, s, t, x) will fit inside a
circle of given diameter. Upper case symbols (A, C, D, G, H, I, N, S, T, X) will have area
equal to that of a circle of given diameter.

Because some symbols require more input data than others, and because the size of
symbols as well as their color can be determined from the input data, the format of data
can be confusing. The general format for the input data is (optional items are in brackets
[]):

x y [ z ] [ size ] [ sigma_x ] [ sigma_y ] [ symbol ]

Thus, the only required input columns are the first two which must contain the longitude
and latitude (or x and y. The remaining items apply when one (or more) of the following
conditions are met:

1. If you want the color of each symbol to be determined individually, supply a CPT
with the -C option and let the 3rd data column contain the z-values to be used with
the CPT.
2. If you want the size of each symbol to be determined individually, append the size in
a separate column.
3. To draw error bars, use the -E option and give one or two additional data columns
with the dx and dy values; the form of -E determines if one (-Ex or -Ey) or two (-Exy)
columns are needed. If upper case flags X or Y are given then we will instead draw a
“box-and-whisker” symbol and the sigma_x (or sigma_y) must represent 4 columns
containing the minimum, the 25 and 75% quartiles, and the maximum value. The
given x (or y) coordinate is taken as the 50% quantile (median).
4. If you draw vectors with -Sv (or -SV) then size is actually two columns containing
the direction (or azimuth) and length of each vector.
5. If you draw ellipses (-Se) then size is actually three columns containing
the direction and the major and minor axes in plot units (with -SE we
expect azimuth instead and axes lengths in km).
Before we try some examples we need to review two key switches; they specify pen
attributes and symbol or polygon fill. Please consult the General Features section the
GMT Technical Reference and Cookbook before experimenting with the examples
below.

Examples:

We will start off using the file tut_data.txt in your directory. Using the GMT
utility gmtinfo we find the extent of the data region:

gmt info @tut_data.txt

which returns

tut_data.txt: N = 7 <1/5> <1/5>

telling us that the file tut_data.txt has 7 records and gives the minimum and maximum
values for the first two columns. Given our knowledge of how to set up linear projections
with -R and -JX, try the following:

1. Plot the data as transparent circles of size 0.3 inches.


2. Plot the data as solid white circles instead.
3. Plot the data using 0.5” stars, making them red with a thick (width = 1.5p), dashed
pen.
To simply plot the data as a line we choose no symbol and specify a pen thickness
instead:

gmt begin GMT_tut_7


gmt set GMT_THEME cookbook
gmt plot @tut_data.txt -R0/6/0/6 -Jx1i -B -Wthinner
gmt end show

Your plot should look like our example 7 below

Result of GMT Tutorial example 7

Exercises:

1. Plot the data as a green-blue polygon instead.


2. Try using a predefined pattern.
A common question is : “How can I plot symbols connected by a line with plot?”. The
surprising answer is that we must call plot twice. While this sounds cumbersome there
is a reason for this: Basically, polygons need to be kept in memory since they may need
to be clipped, hence computer memory places a limit on how large polygons we may
plot. Symbols, on the other hand, can be plotted one at the time so there is no limit to
how many symbols one may plot. Therefore, to connect symbols with a line we must
use the overlay approach:

gmt begin GMT_tut_8


gmt set GMT_THEME cookbook
gmt plot @tut_data.txt -R0/6/0/6 -Jx1i -B -Wthinner
gmt plot tut_data.txt -W -Si0.2i
gmt end show

Your plot should look like our example 8 below. The two-step procedure also makes it
easy to plot the line over the symbols instead of symbols over the line, as here.

Result of GMT Tutorial example 8

Our final plot example involves a more complicated scenario in which we want to plot
the epicenters of several earthquakes over the background of a coastline basemap. We
want the symbols to have a size that reflects the magnitude of the earthquakes, and that
their color should reflect the depth of the hypocenter. The first few lines in the remote
tut_quakes.ngdc looks like this:

Historical Tsunami Earthquakes from the NCEI Database


Year Mo Da Lat+N Long+E Dep Mag
1987 01 04 49.77 149.29 489 4.1
1987 01 09 39.90 141.68 067 6.8

Thus the file has three header records (including the blank line), but we are only
interested in columns 5, 4, 6, and 7. In addition to extract those columns we must also
scale the magnitudes into symbols sizes in inches. Given their range it looks like
multiplying the magnitude by 0.1 will work well for symbol sizes in cm. Reformatting this
file to comply with the plot input format can be done in a number of ways, including
manual editing, using MATLAB, a spreadsheet program, or UNIX tools. Here, we simply
use the common column selection option -i and its scaling/offset capabilities. To skip
the first 3 header records and then select the 4th, 3rd, 5th, and 6th column and scale
the last column by 0.1, we would use

-i4,3,5,6s0.1 -h3

(Remember that 0 is the first column). We will follow conventional color schemes for
seismicity and assign red to shallow quakes (depth 0-100 km), green to intermediate
quakes (100-300 km), and blue to deep earthquakes (depth > 300 km). The quakes.cpt
file establishes the relationship between depth and color:

# color palette for seismicity


#z0 color z1 color
0 red 100 red
100 green 300 green
300 blue 1000 blue

Apart from comment lines (starting with #), each record in the CPT governs the color of
a symbol whose z value falls in the range between z_0 and z_1. If the colors for the
lower and upper levels differ then an intermediate color will be linearly interpolated
given the z value. Here, we have chosen constant color intervals. You may wish to
consult the Color palette tables section in the Cookbook. This color table was generated
as part of the script (below).
We may now complete our example using the Mercator projection:

gmt begin GMT_tut_9


gmt set GMT_THEME cookbook
gmt makecpt -Cred,green,blue -T0,100,300,10000
gmt coast -R130/150/35/50 -JM6i -B -Ggray
gmt plot @tut_quakes.ngdc -Wfaint -i4,3,5,6+s0.1 -h3 -Scc -C
gmt end show

where the c appended to the -Sc option ensures that symbols sizes are interpreted to
be in cm. Your plot should look like our example 9 below

Result of GMT Tutorial example 9

More exercises

1. Select another symbol.


2. Let the deep earthquakes be cyan instead of blue.
Plotting text strings
In many situations we need to annotate plots or maps with text strings; in GMT this is
done using text. Apart from the common switches, there are 9 options that are
particularly useful.

Option Purpose

-Cdx/dy Spacing between text and the text box (see -W)

-Ddx/dy Offsets the projected location of the strings

-
Set font, justify, angle values or source
Fparams

-Gfill Fills the text bos using specified fill

-L Lists the font ids and exits

-N Deactivates clipping at the borders

-Spen Selects outline font and sets pen attributes

-Tform Select text box shape

-Wpen Draw the outline of text box

The input data to text is expected to contain the following information:

[ x y ] [ font] [ angle ] [ justify ] my text

The font is the optional font to use, the angle is the angle (measured counterclockwise)
between the text’s baseline and the horizontal, justify indicates which anchor point on
the text-string should correspond to the given x, y location, and my text is the text string
or sentence to plot. See the Technical reference for the relevant two-character codes
used for justification.

The text string can be one or several words and may include octal codes for special
characters and escape-sequences used to select subscripts or symbol fonts. The
escape sequences that are recognized by GMT are given below:
Code Effect

@~ Turns symbol font on or off

@+ Turns superscript on or off

@- Turns subscript on or off

@# Turns small caps on or off

@_ Turns underline on or off

@%font
Switches to another font; @%% resets to previous font
%

@:size: Switches to another font size; @:: resets to previous size

@;color; Switches to another font color; @;; resets to previous color

@! Creates one composite character of the next two characters

@@ Prints the @ sign itself

Note that these escape sequences (as well as octal codes) can be used anywhere in
GMT, including in arguments to the -B option. A chart of octal codes can be found in
Appendix F in the GMT Technical Reference. For accented European characters you
must set PS_CHAR_ENCODING to ISOLatin1 in your gmt.conf file.

We will demonstrate text with the following script:

gmt begin GMT_tut_10


gmt set GMT_THEME cookbook
gmt text -R0/7/0/5 -Jx1i -B -F+f30p,Times-Roman,DarkOrange+jBL << EOF
1 1 It's P@al, not Pal!
1 2 Try @%33%ZapfChancery@%% today
1 3 @~D@~g@-b@- = 2@~pr@~G@~D@~h.
1 4 University of Hawaii at M@!a\225noa
EOF
gmt end show

Here we have used the “here document” notation in UNIX: The << EOF will treat the
following lines as the input file until it detects the word EOF. There is nothing magical
about the word EOF; you can use any other string like STOP, hellobaby, or IamDone.
Your plot should look like our example 10 below
Result of GMT Tutorial example 10

Code Effect Code Effect

@E Æ @e æ

@O Ø @o ø

@A Å @a å

@C Ç @c ç

@N Ñ @n ñ

@U Ü @u ü

@s ß

Exercises:

1. At y = 5, add the sentence z2=x2+y2𝑧2=𝑥2+𝑦2.


2. At y = 6, add the sentence “It is 32° today”.
Session Three
Contouring gridded data sets
GMT comes with several utilities that can create gridded data sets; we will discuss two
such modules later this session. The data sets needed for this tutorial are obtained via
the Internet as they are needed. Here, we will use grdcut to obtain and extract a GMT-
ready grid that we will next use for contouring:

gmt grdcut @earth_relief_05m -R-66/-60/30/35 -Gtut_bathy.nc -V

Here we use the file extension .nc instead of the generic .grd to indicate that this is a
netCDF file. It is good form, but not essential, to use .nc for netCDF grids. Using that
extension will help other programs installed on your system to recognize these files and
might give it an identifiable icon in your file browser. Learn about other programs that
read netCDF files at the netCDF website. You can also obtain tut_bathy.nc from the
GMT cache server as we are doing below. Feel free to open it in any other program and
compare results with GMT.

We first use the GMT module grdinfo to see what’s in this file:

gmt grdinfo @tut_bathy.nc

The file contains bathymetry for the Bermuda region and has depth values from -5475
to -89 meters. We want to make a contour map of this data; this is a job for grdcontour.
As with previous plot commands we need to set up the map projection with -J. Here,
however, we do not have to specify the region since that is by default assumed to be
the extent of the grid file. To generate any plot we will in addition need to supply
information about which contours to draw. Unfortunately, grdcontour is a complicated
module with too many options. We put a positive spin on this situation by touting its
flexibility. Here are the most useful options:
Option Purpose

-Aannot_int Annotation interval and attributes

-Ccont_int Contour interval

-Ggap Controls placement of contour annotations

-Llow/high Only draw contours within the low to high range

-Qcut Do not draw contours with fewer than cut points

-Ssmooth Resample contours smooth times per grid cell increment

-T[+|-][+dgap[/length]]
Draw tick-marks in downhill
[+l[labels]]

direction for innermost closed contours. Add tick spacing

and length, and characters to plot at the center of closed


contours

-W[a|c]pen Set contour and annotation pens

Subtract offset and multiply data by factor prior to


-Z[+sfactor][+ooffset]
processing

We will first make a plain contour map using 1 km as annotation interval and 250 m as
contour interval. We choose a 7-inch-wide Mercator plot and annotate the borders every
2°:

gmt begin GMT_tut_11


gmt set GMT_THEME cookbook
gmt grdcontour @earth_relief_05m -R-66/-60/30/35 -JM6i -C250 -A1000 -B
gmt end show

Your plot should look like our example 11 below


Result of GMT Tutorial example 11
Exercises:

1. Add smoothing with -S4.


2. Try tick all highs and lows with -T.
3. Skip small features with -Q10.
4. Override region using -R-70/-60/25/35.
5. Try another region that clips our data domain.
6. Scale data to km and use the km unit in the annotations.
Gridding of arbitrarily spaced data
Except in the situation above when a grid file is available, we must convert our data to
the right format readable by GMT before we can make contour plots and color-coded
images. We distinguish between two scenarios:

1. The (x, y, z) data are available on a regular lattice grid.


2. The (x, y, z) data are distributed unevenly in the plane.
The former situation may require a simple reformatting (using xyz2grd), while the latter
must be interpolated onto a regular lattice; this process is known as gridding. GMT
supports three different approaches to gridding; here, we will briefly discuss the two
most common techniques.

All GMT gridding modules have in common the requirement that the user must specify
the grid domain and output filename:

Option Purpose

-Rxmin/xmax/ymin/
The desired grid extent
ymax

The grid spacing (append m or s for minutes or seconds of


-Ixinc[yinc]
arc)

-Ggridfile The output grid filename

Nearest neighbor gridding


Search geometry for nearneighbor.
The GMT module nearneighbor implements a simple “nearest neighbor” averaging
operation. It is the preferred way to grid data when the data density is
high. nearneighbor is a local procedure which means it will only consider the control
data that is close to the desired output grid node. Only data points inside a specified
search radius will be used, and we may also impose the condition that each of
the n sectors must have at least one data point in order to assign the nodal value. The
nodal value is computed as a weighted average of the nearest data point per sector
inside the search radius, with each point weighted according to its distance from the
node. The most important switches are listed below.
Option Purpose

Sets search radius. Append unit for radius in that unit [Default is x-
-Sradius
units]

-Eempty Assign this value to unconstrained nodes [Default is NaN]

-
Sector search, indicate number of sectors [Default is 4]
Nsectors

-W Read relative weights from the 4th column of input data

We will grid the data in the file tut_ship.xyz which contains ship observations of
bathymetry off Baja California. We obtain the file via the cache server as before. We
desire to make a 5’ by 5’ grid. Running gmt info on @tut_ship.xyz yields:

tut_ship.xyz: N = 82970 <245/254.705> <20/29.99131> <-7708/-9>

so we choose the region accordingly, and get a view of the contour map using

gmt begin GMT_tut_12


gmt set GMT_THEME cookbook
gmt nearneighbor -R245/255/20/30 -I5m -S40k -Gship.nc @tut_ship.xyz
gmt grdcontour ship.nc -JM6i -B -C250 -A1000
gmt end show

Your plot should look like our example 12 below


Result of GMT Tutorial example 12
Since the grid ship.nc is stored in netCDF format that is supported by a host of other
modules, you can try one of those as well on the same grid.

Exercises:

1. Try using a 100 km search radius and a 10 minute grid spacing.


Gridding with Splines in Tension

As an alternative, we may use a global procedure to grid our data. This approach,
implemented in the module surface, represents an improvement over standard
minimum curvature algorithms by allowing users to introduce some tension into the
surface. Physically, we are trying to force a thin elastic plate to go through all our data
points; the values of this surface at the grid points become the gridded data.
Mathematically, we want to find the function z(x, y) that satisfies the following equation
away from data constraints:
(1−t)∇2z−t∇z=0,(1−𝑡)∇2𝑧−𝑡∇𝑧=0,
where t is the “tension” in the 0-1 range. Basically, for zero tension we obtain the
minimum curvature solution, while as tension goes toward unity we approach a
harmonic solution (which is linear in cross-section). The theory behind all this is quite
involved and we do not have the time to explain it all here, please see Smith and
Wessel [1990] for details. Some of the most important switches for this module are
indicated below.

Option Purpose

-Aaspect Sets aspect ratio for anisotropic grids.

-Climit Sets convergence limit. Default is 1/1000 of data range.

-
Sets the tension [Default is 0]
Ttension

Preprocessing
The surface module assumes that the data have been preprocessed to eliminate
aliasing, hence we must ensure that this step is completed prior to gridding. GMT
comes with three preprocessors, called blockmean, blockmedian, and blockmode. The
first averages values inside the grid-spacing boxes, the second returns median values,
wile the latter returns modal values. As a rule of thumb, we use means for most smooth
data (such as potential fields) and medians (or modes) for rough, non-Gaussian data
(such as topography). In addition to the required -R and -I switches, these
preprocessors all take the same options shown below:

Option Purpose

-r Choose pixel node registration [Default is gridline]

Append i or o to read or write weights in the 4th


-W[i|o]
column

With respect to our ship data we preprocess it using the median method:

gmt blockmedian -R245/255/20/30 -I5m -V @tut_ship.xyz > ship_5m.xyz


The output data can now be used with surface:

gmt surface ship_5m.xyz -R245/255/20/30 -I5m -Gship.nc -V

If you rerun grdcontour on the new grid file (try it!) you will notice a big difference
compared to the grid made by nearneighbor: since surface is a global method it will
evaluate the solution at all nodes, even if there are no data constraints. There are
numerous options available to us at this point:

1. We can reset all nodes too far from a data constraint to the NaN value.
2. We can pour white paint over those regions where contours are unreliable.
3. We can plot the landmass which will cover most (but not all) of the unconstrained
areas.
4. We can set up a clip path so that only the contours in the constrained region will
show.
Here we have only time to explore the latter approach. The mask module can read the
same preprocessed data and set up a contour mask based on the data distribution.
Once the clip path is activated we can contour the final grid; we finally deactivate the
clipping with a second call to mask. Here’s the recipe:

gmt blockmedian -R245/255/20/30 -I5m -V @tut_ship.xyz > ship_5m.xyz


gmt surface ship_5m.xyz -R245/255/20/30 -I5m -Gship.nc
gmt begin GMT_tut_13
gmt set GMT_THEME cookbook
gmt mask -R245/255/20/30 -I5m ship_5m.xyz -JM6i -B
gmt grdcontour ship.nc -C250 -A1000
gmt mask -C
gmt end show

Your plot should look like our example 13 below


Result of GMT Tutorial example 13
Exercises:

1. Add the continents using any color you want.


2. Color the clip path light gray (use -G in the first mask call).

Session Four
In our final session we will concentrate on color images and perspective views of
gridded data sets. Before we start that discussion we need to cover three important
aspects of plotting that must be understood. These are

1. Color tables and pseudo-colors in GMT.


2. Artificial illumination and how it affects colors.
3. Multi-dimensional grids.
CPTs
The CPT is discussed in detail in the GMT Technical Reference and Cookbook. Please
review the format before experimenting further.

CPTs can be created in any number of ways. GMT provides two mechanisms:

1. Create simple, linear color tables given a master color table (several are built-in) and
the desired z-values at color boundaries (makecpt)
2. Create color tables based on a master CPT color table and the histogram-equalized
distribution of z-values in a gridded data file (grd2cpt)
One can also make these files manually or with awk or other tools. Here we will limit our
discussion to makecpt. Its main argument is the name of the master color table (a list is
shown if you run the module with no arguments) and the equidistant z-values to go with
it. The main options are given below.

Option Purpose

-C Set the name of the master CPT to use

-I Reverse the sense of the color progression

-V Run in verbose mode

-Z Make a continuous rather than discrete table

To make discrete and continuous color CPTs for data that ranges from -20 to 60, with
color changes at every 10, try these two variants:

gmt makecpt -Crainbow -T-20/60/10 > disc.cpt


gmt makecpt -Crainbow -T-20/60/10 -Z > cont.cpt

We can plot these color tables with colorbar; the options worth mentioning here are
listed below. The placement of the color bar is particularly important and we refer you to
the Plot embellishments section for all the details. In addition, the -B option can be used
to set the title and unit label (and optionally to set the annotation-, tick-, and grid-line
intervals for the color bars.). Note that the makecpt commands above are done in
classic mode. If you run makecpt in modern mode then you usually do not specify an
output file via stdout since modern mode maintains what is known as the current CPT.
However, if you must explicitly name an output CPT then you will need to add the -H
option for modern mode to allow output to stdout.

Option Purpose

-Ccpt The required CPT

-Dxxpos/ypos+wlength/ Sets the position and dimensions of scale bar. Append +h to


width[+h] get horizontal bar

-Imax_intensity Add illumination effects

Here is an example of four different ways of presenting the color bar:

gmt begin GMT_tut_14


gmt set GMT_THEME cookbook
gmt makecpt -H -Crainbow -T-20/60/10 > disc.cpt
gmt makecpt -H -Crainbow -T-20/60 > cont.cpt
gmt basemap -R0/6/0/9 -Jx1i -B0 -Xc
gmt colorbar -Dx1i/1i+w4i/0.5i+h -Cdisc.cpt -Ba -B+tdiscrete
gmt colorbar -Dx1i/3i+w4i/0.5i+h -Ccont.cpt -Ba -B+tcontinuous
gmt colorbar -Dx1i/5i+w4i/0.5i+h -Cdisc.cpt -Ba -B+tdiscrete -I0.5
gmt colorbar -Dx1i/7i+w4i/0.5i+h -Ccont.cpt -Ba -B+tcontinuous -I0.5
gmt end show

Your plot should look like our example 14 below


Result of GMT Tutorial example 14
Exercises:

1. Redo the makecpt exercise using the master table hot and redo the bar plot.
2. Try specifying -B10g5.
Illumination and intensities
GMT allows for artificial illumination and shading. What this means is that we imagine
an artificial sun placed at infinity in some azimuth and elevation position illuminating our
surface. The parts of the surface that slope toward the sun should brighten while those
sides facing away should become darker; no shadows are cast as a result of
topographic undulations.

While it is clear that the actual slopes of the surface and the orientation of the sun enter
into these calculations, there is clearly an arbitrary element when the surface is not
topographic relief but some other quantity. For instance, what does the slope toward the
sun mean if we are plotting a grid of heat flow anomalies? While there are many ways to
accomplish what we want, GMT offers a relatively simple way: We may calculate the
gradient of the surface in the direction of the sun and normalize these values to fall in
the -1 to +1 range; +1 means maximum sun exposure and -1 means complete shade.
Although we will not show it here, it should be added that GMT treats the intensities as
a separate data set. Thus, while these values are often derived from the relief surface
we want to image they could be separately observed quantities such as back-scatter
information.

Colors in GMT are specified in the RGB system used for computer screens; it mixes
red, green, and blue light to achieve other colors. The RGB system is a Cartesian
coordinate system and produces a color cube. For reasons better explained in Appendix
I in the Reference book it is difficult to darken and brighten a color based on its RGB
values and an alternative coordinate system is used instead; here we use the HSV
system. If you hold the color cube so that the black and white corners are along a
vertical axis, then the other 6 corners project onto the horizontal plane to form a
hexagon; the corners of this hexagon are the primary colors Red, Yellow, Green, Cyan,
Blue, and Magenta. The CMY colors are the complimentary colors and are used when
paints are mixed to produce a new color (this is how printers operate; they also add
pure black (K) to avoid making gray from CMY). In this coordinate system the angle 0-
360° is the hue (H); the Saturation and Value are harder to explain. Suffice it to say here
that we intend to darken any pure color (on the cube facets) by keeping H fixed and
adding black and brighten it by adding white; for interior points in the cube we will add or
remove gray. This operation is efficiently done in the HSV coordinate system; hence all
GMT shading operations involve translating from RGB to HSV, do the illumination
effect, and transform back the modified RGB values.

Color images
Once a CPT has been made it is relatively straightforward to generate a color image of
a gridded data. Here, we will extract a subset of the global 30” DEM called SRTM30+:

gmt grdcut @earth_relief_30s -R-108/-103/35/40 -Gtut_relief.nc

Using grdinfo we find that the data ranges from about 1000m to about 4300m so we
need to make a CPT with that range.

Color images are made with grdimage which takes the usual common command
options (by default the -R is taken from the data set) and a CPT; the main other options
are:

Option Purpose

-Edpi Sets the desired resolution of the image [Default is data resolution]

-
Use artificial illumination using intensities from intensfile
Iintenfile

-M Force gray shade using the (television) YIQ conversion

We want to make a plain color map with a color bar superimposed above the plot. We
try

gmt begin GMT_tut_15


gmt set GMT_THEME cookbook
gmt makecpt -Crainbow -T1000/5000
gmt grdimage @earth_relief_30s -R-108/-103/35/40 -JM6i -B -BWSnE
gmt colorbar -DJTC -I0.4 -Bxa -By+lm
gmt end show
Your plot should look like our example 15 below
Result of GMT Tutorial example 15
The plain color map lacks detail and fails to reveal the topographic complexity of this
Rocky Mountain region. What it needs is artificial illumination. We want to simulate
shading by a sun source in the east, hence we derive the required intensities from the
gradients of the topography in the N90°E direction using grdgradient. Other than the
required input and output filenames, the available options are

Option -Aazimuth Purpose Azimuthal direction for gradients

-fg Indicates that this is a geographic grid

-N[t|e][+snorm]
Normalize gradients by norm/offset [= 1/0 by default].
[+ooffset]

Insert t to normalize by the inverse tangent transformation.

Insert e to normalize by the cumulative Laplace


distribution.

The GMT inverse tangent transformation shows that raw slopes from bathymetry tend to
be far from normally distributed (left). By using the inverse tangent transformation we
can ensure a more uniform distribution (right). The inverse tangent transform simply
takes the raw slope estimate (the x value at the arrow) and returns the corresponding
inverse tangent value (normalized to fall in the plus/minus 1 range; horizontal arrow
pointing to the y-value).

How the inverse tangent operation works. Raw slope values (left) are processed via the
inverse tangent operator, turning tan(x) into x and thus compressing the data range.
The transformed slopes are more normally distributed (right).
-Ne and -Nt yield well behaved gradients. Personally, we prefer to use the -Ne option;
the value of norm is subjective and you may experiment somewhat in the 0.5-5 range.
For our case we choose

gmt grdgradient @tut_relief.nc -Ne0.8 -A100 -fg -Gus_i.nc

Given the CPT and the two gridded data sets we can create the shaded relief image:

gmt begin GMT_tut_16


gmt set GMT_THEME cookbook
gmt makecpt -Crainbow -T1000/5000
gmt grdcut @earth_relief_30s -R-108/-103/35/40 -Gtut_relief.nc
gmt grdgradient tut_relief.nc -Ne0.8 -A100 -fg -Gus_i.nc
gmt grdimage @earth_relief_30s -R-108/-103/35/40 -Ius_i.nc -JM6i -B -BWSnE
gmt colorbar -DJTC -I0.4 -Bxa -By+lm
gmt end show

Your plot should look like our example 16 below


Result of GMT Tutorial example 16
Exercises:

1. Force a gray-shade image.


2. Rerun grdgradient with -N1.
Multi-dimensional maps
Climate data, like ocean temperatures or atmospheric pressure, are often provided as
multi-dimensional (3-D, 4-D or 5-D) grids in netCDF format. This section will
demonstrate that GMT is able to plot “horizontal” slices (spanning latitude and
longitude) of such grids without much effort.

As an example we will download the Seasonal Analysed Mean Temperature from


the World Ocean Atlas 1998 The file in question is named otemp.anal1deg.nc
(ftp://ftp.cdc.noaa.gov/Datasets/nodc.woa98/temperat/seasonal/otemp.anal1deg.nc).

You can look at the information pertained in this file using the program ncdump and
notice that the variable that we want to plot (otemp) is a four-dimensional variable of
time, level (i.e., depth), latitude and longitude.

ncdump -h otemp.anal1deg.nc

We will need to make an appropriate color scale, running from -2°C (freezing
temperature of salt water) to 30°C (highest likely ocean temperature). Let us focus on
the temperatures in Summer (that is the third season, July through September) at sea
level (that is the first level). To plot these in a Mollweide projection we use:

gmt begin GMT_tut_17


gmt set GMT_THEME cookbook
gmt makecpt -Cno_green -T-2/30/2
gmt grdimage -Rg -JW180/9i "@otemp.anal1deg.nc?otemp[2,0]" -Bag
gmt end show

The addition “?otemp[2,0]” indicates which variable to retrieve from the netCDF file
(otemp) and that we need the third time step and first level. The numbering of the time
steps and levels starts at zero, therefore “[2,0]”. Make sure to put the whole file name
within quotes since the characters ?, [ and ] have special meaning in Unix. Your plot
should look like our example 17 below

Result of GMT Tutorial example 17


Exercises:
1. Plot the temperatures for Spring at 5000 m depth. (Hint: use ncdump -v level to
figure out what level number that is).
2. Include a color scale at the bottom of the plot.
Perspective views
Our final undertaking in this tutorial is to examine three-dimensional perspective views.
The GMT module that produces perspective views of gridded data files is grdview. It
can make two kinds of plots:

1. Mesh or wire-frame plot (with or without superimposed contours)


2. Color-coded surface (with optional shading, contours, or draping).
Regardless of plot type, some arguments must be specified; these are

1. relief_file; a gridded data set of the surface.


2. -J for the desired map projection.
3. -JZheight for the vertical scaling.
4. -pazimuth/elevation for the vantage point.
In addition, some options may be required:

Option Purpose

-Ccpt The cpt is required for color-coded surfaces and for contoured mesh plots

-
Gdrape_fi Assign colors using drape_file instead of relief_file
le

-
Iintens_fil File with illumination intensities
e

-Qm Selects mesh plot

Surface plot using polygons; append +m to show mesh. This option allows for -
-Qs[+m]
W

Image by scan-line conversion. Specify dpi; append g to force gray-shade


-Qidpi[g]
image. -B is disabled.

-Wpen Draw contours on top of surface (except with -Qi)


Mesh-plot

Mesh plots work best on smaller data sets. We again use the small subset of the
ETOPO5 data over Bermuda and will use the ocean CPT. A simple mesh plot can
therefore be obtained with

gmt begin GMT_tut_18


gmt set GMT_THEME cookbook
gmt grdview @earth_relief_05m -R-66/-60/30/35 -JM5i -JZ2i -p135/30 -B
gmt end show

Your plot should look like our example 18 below


Result of GMT Tutorial example 18
Exercises:

1. Select another vantage point and vertical height.


Color-coded view

We will make a perspective, color-coded view of the US Rockies from the southeast.
This is done using

gmt begin GMT_tut_19


gmt set GMT_THEME cookbook
gmt makecpt -Cdem2 -T1000/5000
gmt grdcut @earth_relief_30s -R-108/-103/35/40 -Gtut_relief.nc
gmt grdgradient tut_relief.nc -Ne0.8 -A100 -fg -Gus_i.nc
gmt grdview tut_relief.nc -JM4i -p135/35 -Qi50 -Ius_i.nc -B -JZ0.5i
gmt end show

Your plot should look like our example 19 below

Result of GMT Tutorial example 19


This plot is pretty crude since we selected 50 dpi but it is fast to render and allows us to
try alternate values for vantage point and scaling. When we settle on the final values we
select the appropriate dpi for the final output device and let it rip.
Exercises:

1. Choose another vantage point and scaling.


2. Redo grdgradient with another illumination direction and plot again.
3. Select a higher dpi, e.g., 200.

Modules
Note

Looking for the classic mode modules like psxy and pscoast ? See the equivalent page
for classic mode.

This is a list of all GMT core and supplemental modules and their uses, as well as some
utility scripts. All modules are requested via a call to the gmt program.

Program
 gmt
Core Modules
 basemap  fitcircle  gmtsplit  grdhisteq  greenspline
 batch  gmt2kml  gmtvector  grdimage  histogram
 begin  gmtbinstats  gmtwhich  grdinfo  image
 blockmean  gmtconnect  grd2cpt  grdinterpolate  inset
 blockmedian  gmtconvert  grd2kml  grdlandmask  kml2gmt
 blockmode  gmtdefaults  grd2xyz  grdmask  legend
 clear  grdgdal  grdblend  grdmath  makecpt
 clip  gmtget  grdclip  grdmix  mapproject
 coast  gmtinfo  grdcontour  grdpaste  mask
 colorbar  gmtlogo  grdconvert  grdproject  movie
 contour  gmtmath  grdcut  grdsample  nearneighbor
 dimfilter  gmtregress  grdedit  grdtrack  plot
 docs  gmtselect  grdfft  grdtrend  plot3d
 end  gmtset  grdfill  grdvector  project
 events  gmtsimplify  grdfilter  grdview  psconvert
 figure  gmtspatial  grdgradient  grdvolume  rose
 filter1d
Supplemental Modules
 earthtide  mgd77magref  grdgravmag3d  coupe  grdspotter
 gpsgridder  mgd77manage  grdredpol  meca  hotspotter
 velo  mgd77path  grdseamount  polar  originater
 gshhg  mgd77sniffer  talwani2d  sac  polespotter
 img2grd  mgd77track  talwani3d  backtracker  rotconverter
 mgd77convert  gmtflexure  segy2grd  gmtpmodeler  rotsmoother
 mgd77header  gmtgravmag3d  segy  grdpmodeler  x2sys_binlist
 mgd77info  gravfft  segyz  grdrotater  x2sys_cross
 mgd77list  grdflexure
Utility Scripts
 gmt-config  gmt5syntax  gmt_shell_functions.sh  gmtswitch
Session management
begin Initiate a new GMT modern mode session

Delete current default settings, or the cache, data, geography or sessions


clear
directories

docs Show HTML documentation of specified module

end Terminate GMT modern mode session and produce optional graphics

figure Set attributes for the current modern mode session figure

inset Manage figure inset setup and completion

subplot Manage modern mode figure subplot configuration and selection

Plotting
basemap Plot base maps and frames

clip Initialize or terminate polygonal clip paths

coast Plot continents, countries, shorelines, rivers, and borders


colorbar Plot gray scale or color scale bar

contour Contour table data by direct triangulation

events Plot event symbols, lines, polygons and labels for a moment in time

gmtlogo Plot the GMT logo

grdcontou
Make contour map using a grid
r

grdimage Project and plot grids or images

grdvector Plot vector field from two component grids

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

histogram Calculate and plot histograms

image Plot raster or EPS images

legend Plot a legend

mask Clip or mask map areas with no data table coverage

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

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

rose Plot a polar histogram (rose, sector, windrose diagrams)

solar Plot day-light terminators and other sunlight parameters

ternary Plot data on ternary diagrams

text Plot or typeset text

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

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

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


blockmedian
estimation

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


dimfilter Directional filtering of grids in the space domain

filter1d Time domain filtering of 1-D data tables

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

Gridding
greenspline Interpolate using Green’s functions for splines in 1-3 dimensions

nearneighbo
Grid table data using a "Nearest neighbor" algorithm
r

sphinterpola
Spherical gridding in tension of data on a sphere
te

surface Grid table data using adjustable tension continuous curvature splines

triangulate Delaunay triangulation or Voronoi partitioning and gridding of Cartesian data

grdinterpola Interpolate a 3-D cube, 2-D grids or 1-D series from a 3-D data cube or stack
te of 2-D grids

Sampling of 1-D and 2-D data


gmtsimplif
Line reduction using the Douglas-Peucker algorithm
y

grdsample Resample a grid onto a new lattice

grdtrack Sample grids at specified (x,y) locations

sample1d Resample 1-D table data using splines

Projection and map-transformation


grdproject Forward and inverse map transformation of grids

Forward and inverse map transformations, datum conversions and


mapproject
geodesy

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

Information retrieval
gmtdefault
List current GMT default settings
s

gmtget Get individual GMT default settings or download data sets

gmtinfo Get information about data tables

gmtset Change individual GMT default settings

grdinfo Extract information from 2-D grids or 3-D cubes

Mathematical operations on tables or grids


gmtmath Reverse Polish Notation (RPN) calculator for data tables

makecpt Make GMT color palette tables

spectrum1d Compute auto- [and cross-] spectra from one [or two] time series

sph2grd Compute grid from spherical harmonic coefficients

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

sphtriangulat
Delaunay or Voronoi construction of spherical data
e

Convert or extract subsets of data


gmtbinstats Bin spatial data and determine statistics per bin

gmtconnect Connect individual lines whose end points match within tolerance

gmtconvert Convert, paste, or extract columns from data tables

gmtselect Select data table subsets based on multiple spatial criteria

gmtspatial Geospatial operations on points, lines and polygons

gmtsplit Split xyz[dh] data tables into individual segments

gmtvector Operations on Cartesian vectors in 2-D and 3-D

grd2kml Create KML image quadtree from single grid

grd2xyz Convert grid to data table

grdblend Blend several partially overlapping grids into one larger grid
grdconvert Convert between different grid formats

grdcut Extract subregion from a grid

grdpaste Join two grids along their common edge

xyz2grd Convert data table to a grid

Trends in 1-D and 2-D data


fitcircle Find mean position and great [or small] circle fit to points on sphere

gmtregres
Linear regression of 1-D data sets
s

grdtrend Fit trend surface to grids and compute residuals

trend1d Fit [weighted] [robust] polynomial/Fourier model for y = f(x) to xy[w] data

trend2d Fit [weighted] [robust] polynomial for z = f(x,y) to xyz[w] data

Grid operations
grd2cpt Make linear or histogram-equalized color palette table from grid

grdclip Clip the range of grid values

grdedit Modify header or content of a grid

grdfft Mathematical operations on grids in the spectral domain

grdfill Interpolate across holes in a grid

grdgradient Compute directional gradients from a grid

grdhisteq Perform histogram equalization for a grid

grdlandmas
Create a "wet-dry" mask grid from shoreline data base
k

grdmask Create mask grid from polygons or point coverage

grdmath Reverse Polish Notation (RPN) calculator for grids (element by element)

grdmix Blending and transforming grids and images

grdvolume Calculate grid volume and area constrained by a contour


Miscellaneous
batch Automate batch job processing

gmt2kml Convert GMT data table to Google Earth KML file

grdgdal Execute GDAL raster programs from GMT

gmtwhich Find full path to specified files

kml2gmt Extract GMT table data from Google Earth KML files

movie Create animation sequences and movies

psconvert Convert [E]PS file(s) to other formats using Ghostscript

geodesy
earthtide Compute grids or time-series of solid Earth tides

gpsgridde
Interpolate GPS strains using Green’s functions for elastic deformation
r

velo Plot velocity vectors, crosses, anisotropy bars and wedges

GSHHG
Extract data tables from binary GSHHG or WDBII data
gshhg
files

IMG
Extract a subset from an img file in Mercator or Geographic
img2grd
format

MGD77
mgd77convert Convert MGD77 data to other formats

mgd77header Create MGD77 headers from A77 files

mgd77info Extract information about MGD77 files

mgd77list Extract data from MGD77 files


mgd77magref Evaluate the IGRF or CM4 magnetic field models

mgd77manag
Manage the content of MGD77+ files
e

mgd77path Return paths to MGD77 cruises and directories

mgd77sniffer Along-track quality control of MGD77 cruises

mgd77track Plot track-lines of MGD77 cruises

potential
gmtflexure Compute flexural deformation of 2-D loads, forces, and bending moments

gmtgravma Compute the gravity/magnetic anomaly of a 3-D body by the method of


g3d Okabe

gravfft Spectral calculations of gravity, isostasy, admittance, and coherence for grids

grdflexure Compute flexural deformation of 3-D surfaces for various rheologies

grdgravmag
Computes the gravity effect of one (or two) grids by the method of Okabe
3d

grdredpol Compute the Continuous Reduction To the Pole, AKA differential RTP

grdseamoun Create synthetic seamounts (Gaussian, parabolic, polynomial, cone or disc;


t circular or elliptical)

talwani2d Compute geopotential anomalies over 2-D bodies by the method of Talwani

talwani3d Compute geopotential anomalies over 3-D bodies by the method of Talwani

SEGY
segyz Plot a SEGY file in 3-D

segy Plot a SEGY file in 2-D

segy2gr
Converting SEGY data to a grid
d

seis
coupe Plot cross-sections of focal mechanisms
meca Plot focal mechanisms

polar Plot polarities on the lower hemisphere of the focal sphere

sac Plot seismograms in SAC format

spotter
backtracker Generate forward and backward flowlines and hotspot tracks

gmtpmodeler Evaluate a plate motion model at given locations

grdpmodeler Evaluate a plate motion model on a geographic grid

grdrotater Finite rotation reconstruction of geographic grid

grdspotter Create CVA grid from a gravity or topography grid

hotspotter Create CVA grid from seamount locations

originater Associate seamounts with nearest hotspot point sources

polespotter Find stage poles given fracture zones and abyssal hills

rotconverter Manipulate total reconstruction and stage rotations

Get mean rotations and covariance matrices from set of finite


rotsmoother
rotations

x2sys
x2sys_binlist Create bin index listing from track data files

x2sys_cross Calculate crossovers between track data files

x2sys_datalis
Extract content of track data files
t

x2sys_get Get track listing from track index database

x2sys_init Initialize a new x2sys track database

x2sys_list Extract subset from crossover data base

x2sys_merge Merge an updated COEs table (smaller) into the main table (bigger)

x2sys_put Update track index database from track bin file


x2sys_report Report statistics from crossover data base

x2sys_solve Determine least-squares systematic correction from crossovers

gmt
The Generic Mapping Tools data processing and display software package

Introduction
GMT is a collection of freely available command-line tools under the GNU LGPL that
allows you to manipulate x,y and x,y,z data sets (filtering, trend fitting, gridding,
projecting, etc.) and produce illustrations ranging from simple x-y plots, via contour
maps, to artificially illuminated surfaces and 3-D perspective views in black/white or full
color. Linear, log10, and power scaling is supported in addition to over 30 common map
projections. The processing and display routines within GMT are completely general
and will handle any (x,y) or (x,y,z) data as input.
Synopsis
gmt is the main program that can start any of the modules:

gmt module module-options

Starts a given GMT module with the module-options that pertain to that particular
module. A few special commands are also available:
gmt clear items

Deletes current defaults, or the cache, data or sessions directories. Choose


between defaults (deletes the current gmt.conf file used for the current modern
session), cache (deletes the user’s cache directory and all of its
content), data (deletes the user’s data download directory and all of its content),
or all (does all of the above).
gmt begin [session-prefix] [format] [options]

Initializes a new GMT session under modern mode [Default is classic mode]. All
work is performed in a temporary work directory. The optional session-
prefix assigns a name to the session, and this may be used as figure name for
single-figure sessions [gmtsession]. Likewise, the optional format can be used to
override the default graphics format [PDF].
gmt figure prefix [format(s)] [options]

Specifies the desired name, output format(s) and any custom arguments that
should be passed to psconvert when producing this figure. All subsequent
plotting will be directed to this current figure until another gmt figure command is
issued or the session ends. The prefix is used to build final figure names when
extensions are automatically appended. The format setting is a comma-
separated list of desired extensions (e.g., pdf,png).
gmt inset [arguments]

Allows users to place a map inset by temporarily changing where plotting takes
place as well as the region and projection, then resets to previous stage.
gmt subplot [arguments]
Allows users to create a matrix of panels with automatic labeling and
advancement.
gmt end [show]

Terminates a GMT modern mode session and automatically converts the


registered illustration(s) to their specified formats, then eliminates the temporary
work directory. The figures are placed in the current directory.

For information on any module, load the module documentation in your browser via
gmt docs, e.g.:

gmt docs grdimage

If no module is given then several other options are available:

--help

List and description of GMT modules.


--new-script[=L]

Write a GMT modern mode script template to stdout. Optionally append the
desired scripting language among bash, csh, or batch. Default is the main shell
closest to your current shell (e.g., bash for zsh, csh for tcsh).
--new-glue=name

Write the C code glue needed when building third-party supplements as shared
libraries. The name is the name of the shared library. Run gmt in the directory of
the supplement and the glue code will be written to stdout. Including this C code
when building the shared library means gmt can list available modules via the --
show-modules, --help options. We recommend saving the code to
gmt_name_glue.c.
--show-bindir

Show directory of executables and exit.


--show-citation

Show the citation for the latest GMT publication.


--show-classic

List classic module names on stdout and exit.


--show-classic-core

List classic module names (core only) on stdout and exit.


--show-cores

Show number of available cores.


--show-datadir

Show data directory/ies and exit.


--show-dataserver

Show URL of the remote GMT data server.


--show-doi

Show the DOI of the current release.


--show-modules

List modern module names on stdout and exit.


--show-modules-core

List modern module names (core only) on stdout and exit.


--show-library

Show the path of the shared GMT library.


--show-plugindir

Show plugin directory and exit.


--show-sharedir

Show share directory and exit.


--show-userdir

Show full path of user’s ~/.gmt dir and exit.


--version

Print version and exit.


=

Check if that module exist and if so the program will exit with status of 0;
otherwise the status of exit will be non-zero.

Command-line completion
GMT provides basic command-line completion (tab completion) for bash. The
completion rules are either installed
in /etc/bash_completion.d/gmt or <prefix>/share/tools/gmt_completion.bash . Depending
on the distribution, you may still need to source the gmt completion file
from ~/.bash_completion or ~/.bashrc . For more information see Section Command-line
completion in the CookBook.

GMT Modules
Run gmt --help to print the list of all core and supplementals modules within GMT, and
a very short description of their purpose. Detailed information about each program can
be found in the separate manual pages.

Custom Modules
The gmt program can also load custom modules from shared libraries built as specified
in the GMT API documentation. This way your modules can benefit from the GMT
infrastructure and extend GMT in specific ways.

The Common GMT Options


-B[p|s]parameters -Jparameters -Jz|Zparameters -Rwest/east/south/north[/zmin/zmax]
[+r][+uunit] -U[stamp] -V[level] -X[a|c|f|r][xshift] -Y[a|c|f|r][yshift] -aflags -bbinary -
crow,col|index -dnodata -eregexp -fflags -ggaps -hheaders -iflags -jflags -lflags -nflags
-oflags -pflags -qflags -rreg -sflags -ttransp -x[[-]n] -:[i|o]

Description
These are all the common GMT options that remain the same for all GMT modules. No
space between the option flag and the associated arguments.
The -B option

Syntax

-B[p|s]parameters

Set map boundary frame and axes attributes. (See cookbook information).

Description

This is potentially the most complicated option in GMT, but most examples of its usage
are actually quite simple. We distinguish between two sets of information: Frame
settings and Axes settings. These are set separately by their own -B invocations; hence
multiple -B specifications may be specified. The Frame settings cover things such as
which axes should be plotted, canvas fill, plot title (and subtitle), and what type of
gridlines be drawn, whereas the Axes settings deal with annotation, tick, and gridline
intervals, axes labels, and annotation units.

Frame settings

The Frame settings are specified by

-B[axes][+b][+gfill][+i[val]][+n][+olon/lat][+ssubtitle][+ttitle][+w[pen]][+xfill][+yfill][+zfill]

The frame setting is optional but can be invoked once to override the defaults. The
following modifiers can be appended to -B to control the Frame settings:

 axes to set which of the axes should be drawn and possibly annotated using a
combination of the codes listed below [default is theme dependent]. Borders omitted
from the set of codes will not be drawn. For example, WSn denotes that the
“western” (left) and “southern” (bottom) axes should be drawn with tick-marks and
annotations by using W and S; that the “northern” (top) edge of the plot should be
drawn with tick-marks and without annotations by using n; and that the “eastern”
(right) axes should not be drawn by not including one of E|e|r.

o West, East, South, North, and/or (for 3-D plots) Z indicate axes that should be
drawn with both tick-marks and annotations.
o west, east, south, north, and/or (for 3-D plots) z indicate axes that should be
drawn with tick-marks but without annotations.
o l(eft), r(ight), b(ottom), t(op) and/or (for 3-D plots) u(p) indicate axes that
should be drawn without tick-marks or annotations.

 Z|zcode (for 3-D plots) where code is any combination of the corner ids 1, 2, 3, 4. By
default, a single vertical axes will be plotted for 3-D plots at the most suitable map
corner. code can be used to override this, where 1 represents the south-western
(lower-left) corner, 2 the south-eastern (lower-right), 3 the north-eastern (upper-
right), and 4 the north-western (upper-left) corner.
 +w[pen] (for 3-D plots) to draw the outlines of the x-z and y-z planes [default is no
outlines]. Optionally, append pen to specify different pen attributes [default
is MAP_GRID_PEN_PRIMARY].
 +b (for 3-D plots) to draw the foreground lines of the 3-D cube defined by -R.
 +gfill to paint the interior of the canvas with a color specified by fill [default is no fill].
This also sets fill for the two back-walls in 3-D plots.
 +xfill to paint the yz plane with a color specified by fill [default is no fill].
 +yfill to paint the xz plane with a color specified by fill [default is no fill].
 +zfill to paint the xy plane with a color specified by fill [default is no fill].
 +i[val] to annotate an internal meridian or parallel when the axis that normally would
be drawn and annotated does not exist (e.g., for an azimuthal map with 360-degree
range that has no latitude axis or a global Hammer map that has no longitude
axis). val gives the meridian or parallel that should be annotated [default is 0].
 +olon/lat to produce oblique gridlines about another pole specified by lon/lat [default
references to the North pole]. +o is ignored if no gridlines are requested.
 +n to have no frame and annotations at all [default is contolled by axes].
 +ttitle to place the string given in title centered above the plot frame [default is no
title].
 +ssubtitle (requires +ttitle) to place the string given in subtitle beneath
the title [default is no subtitle].
Note: Both +ttitle and +ssubtitle may be set over multiple lines by breaking them up
using the markers @^ or <break>. To include LaTeX code as part of a single-line title or
subtitle, enclose the expression with @[ markers (or alternatively <math> … </math>)
(requires latex and dvips to be installed). See the Using LaTeX Expressions in
GMT chapter for more details.
Axes settings

The Axes settings are specified by

-B[p|s][x|y|z]intervals[+aangle|n|p][+f][+llabel][+pprefix][+uunit]

but you may also split this into two separate invocations for clarity, i.e.,

-B[p|s][x|y|z][+aangle|n|p][+f][+l|Llabel][+pprefix][+s|Sseclabel][+uunit]
-B[p|s][x|y|z]intervals

The following modifiers can be appended to -B to control the Axes settings:

 p|s to set whether the modifiers apply to the p(rimary) or s(econdary) axes [Default
is p]. These settings are mostly used for time axes annotations but are available for
geographic axes as well. Note: Primary refers to annotations closest to the axis and
secondary to annotations further away. Hence, primary annotation-, tick-, and
gridline-intervals must be shorter than their secondary counterparts. The terms
“primary” and “secondary” do not reflect any hierarchical order of units: the “primary”
annotation interval is usually smaller (e.g., days) while the “secondary” annotation
interval typically is larger (e.g., months).
 x|y|z to set which axes the modifiers apply to [default is xy]. If you wish to give
different annotation intervals or labels for the various axes then you must repeat
the B option for each axis. For a 3-D plot with the -p and -Jz options used, -Bz can
be used to provide settings for the verical axis.
 +f (for geographic axes only) to give fancy annotations with W|E|S|N suffices
encoding the sign.
 +l|+Llabel (for Cartesian plots only) to add a label to an axis. +l uses the default
label orientation; +L forces a horizontal label for y-axes, which is useful for very
short labels.
 +s|Sseclabel (for Cartesion plots only) to specify an alternate label for the right or
upper axes. +s uses the default label orientation; +S forces a horizontal label for y-
axes, which is useful for very short labels.
 +pprefix (for Cartesion plots only) to define a leading text prefix for the axis
annotation (e.g., dollar sign for plots related to money). For geographic maps the
addition of degree symbols, etc. is automatic and controlled
by FORMAT_GEO_MAP.
 +uunit (for Cartesion plots only) to append specific units to the annotations. For
geographic maps the addition of degree symbols, etc. is automatic and controlled
by FORMAT_GEO_MAP.
 +aangle (for Cartesion plots only) to plot slanted annotations, where angle is
measured with respect to the horizontal and must be in the -90 <= angle <= 90
range. +an can be used as a shorthand for normal (i.e., +a90) [Default for y-axis]
and +ap for parallel (i.e., +a0) annotations [Default for x-axis]. These defaults can be
changed via MAP_ANNOT_ORTHO.
 intervals to define the intervals for annotations and major tick spacing, minor tick
spacing, and/or grid line spacing. See Intervals Specification for the formatting
associated with this modifier.
NOTE: To include LaTeX code as part of a label, enclose the expression with
@[ markers (or alternatively <math> … </math>). (requires latex and dvips to be
installed). See the Using LaTeX Expressions in GMT chapter for more details.

NOTE: If any labels, prefixes, or units contain spaces or special characters you will
need to enclose them in quotes.

NOTE: Text items such as title, subtitle, label and seclabel are seen by GMT as part of
a long string containing everything passed to -B. Therefore, they cannot contain
substrings that look like other modifiers. If you need to embed such sequences
(e.g., +t“Solving a+b=c”) you need to replace those + symbols with their octal
equivalent \053, (e.g., +t“Solving a\053b=c”).

NOTE: For non-geographical projections: Give negative scale (in -Jx) or axis length (in -
JX) to change the direction of increasing coordinates (i.e., to make the y-axis positive
down).

Intervals specification
The intervals specification is a concatenated string made up of substrings of the
form

[a|f|g][stride][phase][unit].

The choice of a|f|g sets the axis item of interest, which are detailed in the Table interval
types. Optionally, append phase to shift the annotations by that amount (positive or
negative with the sign being required). Optionally, append unit to specify the units
of stride, where unit is one of the 18 supported unit codes. For custom annotations and
intervals, intervals can be given as cintfile, where intfile contains any number of records
with coord type [label]. See the section Custom axes for more details.

Flag Description

a Annotation and major tick spacing

f Minor tick spacing

g Grid line spacing

NOTE: The appearance of certain time annotations (month-, week-, and day-names)
may be affected by the GMT_LANGUAGE, FORMAT_TIME_PRIMARY_MAP,
and FORMAT_TIME_SECONDARY_MAP settings.

Automatic intervals: GMT will auto-select the spacing between the annotations and
major ticks, minor ticks, and grid lines if stride is not provided after a|f|g. This can be
useful for automated plots where the region may not always be the same, making it
difficult to determine the appropriate stride in advance. For example, -Bafg will select all
three spacings automatically for both axes. In case of longitude–latitude plots, this will
keep the spacing the same on both axes. You can also use -Bxafg -Byafg to auto-
select them separately. Note that given the myriad ways of specifying time-axis
annotations, the automatic selections may need to be overridden with manual settings
to achieve exactly what you need. When stride is omitted after g, the grid line are
spaced the same as the minor ticks; unless g is used in consort with a, in which case
the grid lines are spaced the same as the annotations.

Stride units: The unit flag can take on one of 18 codes which are listed in Table Units.
Almost all of these units are time-axis specific. However, the d, m, and s units will be
interpreted as arc degrees, minutes, and arc seconds respectively when a map
projection is in effect.

Fla
Unit Description
g

Y year Plot using all 4 digits

y year Plot using last 2 digits


Fla
Unit Description
g

O month Format annotation using FORMAT_DATE_MAP

o month Plot as 2-digit integer (1–12)

U ISO week Format annotation using FORMAT_DATE_MAP

u ISO week Plot as 2-digit integer (1–53)

Gregorian
r 7-day stride from start of week (see TIME_WEEK_START)
week

K ISO weekday Plot name of weekday in selected language

k weekday Plot number of day in the week (1–7) (see TIME_WEEK_START)

D date Format annotation using FORMAT_DATE_MAP

Plot day of month (1–31) or day of year (1–366)


d day
(see FORMAT_DATE_MAP)

Same as d; annotations aligned with week


R day
(see TIME_WEEK_START)

H hour Format annotation using FORMAT_CLOCK_MAP

h hour Plot as 2-digit integer (0–24)

M minute Format annotation using FORMAT_CLOCK_MAP

m minute Plot as 2-digit integer (0–60)

S seconds Format annotation using FORMAT_CLOCK_MAP

s seconds Plot as 2-digit integer (0–60)

NOTE: If your axis is in radians you can use multiples or fractions of pi to set such
annotation intervals. The format is [s]pi[f], for an optional integer scale s and optional
integer fraction f. When GMT parses one of these forms we alert the labeling machinery
to look for certain combinations of pi, limited to npi, 3/2 pi (3pi2), and fractions 3/4
(3pi4), 2/3 (2pi3), 1/2 (1pi2), 1/3 (1pi3), and 1/4 (1pi4) in the interval given to the -

combinations we typeset the label using the Greek letter π𝜋 and required multiples or
B axes settings. When an annotated value is within roundoff-error of these

fractions.
NOTE: These GMT parameters can affect the appearance of the map boundary:

MAP_ANNOT_MIN_ANGLE, MAP_ANNOT_MIN_SPACING, FONT_ANNOT_P


RIMARY, FONT_ANNOT_SECONDARY, MAP_ANNOT_OFFSET_PRIMARY, M
AP_ANNOT_OFFSET_SECONDARY, MAP_ANNOT_ORTHO, MAP_FRAME_A
XES, MAP_DEFAULT_PEN, MAP_FRAME_TYPE, FORMAT_GEO_MAP, MAP_
FRAME_PEN, MAP_FRAME_WIDTH, MAP_GRID_CROSS_SIZE_PRIMARY, M
AP_GRID_PEN_PRIMARY, MAP_GRID_CROSS_SIZE_SECONDARY, MAP_G
RID_PEN_SECONDARY, FONT_TITLE, FONT_LABEL, MAP_LINE_STEP, MA
P_ANNOT_OBLIQUE, FORMAT_CLOCK_MAP, FORMAT_DATE_MAP, FORM
AT_TIME_PRIMARY_MAP, FORMAT_TIME_SECONDARY_MAP, GMT_LANG
UAGE, TIME_WEEK_START, MAP_TICK_LENGTH_PRIMARY,
and MAP_TICK_PEN_PRIMARY; see the gmt.conf man page for details.

The -J option

Syntax

-Jparameters

Specify the projection. (See cookbook summary) (See projections table).

Description

Select map projection. The first character of parameters determines the projection. If the
character is upper case then the argument(s) supplied as scale(s) is interpreted to be
the map width (or axis lengths), else the scale argument(s) is the map scale (see its
definition for each projection). The measurement unit (called UNIT below) is cm, inch, or
point, depending on the PROJ_LENGTH_UNIT setting in gmt.conf, but this can be
overridden on the command line by appending c, i, or p to the scale or width values.
Append +dh, +du, or +dl to the given width if you instead want to set the map height,
the maximum (upper) dimension, or the minimum (lower) dimension, respectively
[Default is +dw for width]. In case the central meridian is an optional parameter and it is
being omitted, then the center of the longitude range given by the -R option is used. The
default standard parallel is the equator. The ellipsoid used in map projections is user-
definable. 73 commonly used ellipsoids and spheroids are currently supported, and
users may also specify their own custom ellipsoid parameters [Default is WGS-84].
Several GMT parameters can affect the
projection: PROJ_ELLIPSOID, GMT_INTERPOLANT, PROJ_SCALE_FACTOR,
and PROJ_LENGTH_UNIT; see the gmt.conf man page for details. Choose one of the
following projections and append the required parameters (The E or C after projection
names stands for Equal-Area and Conformal, respectively):

CYLINDRICAL PROJECTIONS:

-Jc|Clon0/lat0/scale|width (Cassini).

Give projection center lon0/lat0 and either scale (with -Jc; as 1:xxxx or plot-
units/degree) or width (with -JC; in plot-units).

-Jcyl_stere|Cyl_stere/[lon0/[lat0/]]scale|width (Cylindrical Stereographic)

Give central meridian lon0 (optional), standard parallel lat0 (optional), and
either scale along parallel (with -Jcyl_stere; as 1:xxxx or plot-units/degree)
or width (with -JCyc_stere; in plot-units). The standard parallel is typically one of these
(but can be any value):

 66.159467 - Miller’s modified Gall


 55 - Kamenetskiy’s First
 45 - Gall’s Stereographic
 30 - Bolshoi Sovietskii Atlas Mira or Kamenetskiy’s Second
 0 - Braun’s Cylindrical

-Jj|J[lon0/]scale|width (Miller Cylindrical Projection).

Give the central meridian lon0 (optional) and either scale (with -Jj; as 1:xxxx or plot-
units/degree) or width (with -JJ; in plot-units).

-Jm|M[lon0/[lat0/]]scale|width (Mercator [C])

Give central meridian lon0 (optional), standard parallel lat0 (optional), and
either scale along parallel (with -Jm; as 1:xxxx or plot-units/degree) or width (with -JM;
in plot-units).

-Joparameters[+v] (Oblique Mercator [C]).


Typically used with -RLLx/LLy/URx/URy+r or with projected coordinates. Specify one of:

-Jo|O[a|A]lon0/lat0/azimuth/scale|width[+v]

Set projection center lon0/lat0, azimuth of oblique equator,


and scale or width

-Jo|O[b|B]lon0/lat0/lon1/lat1/scale|width[+v]

Set projection center lon0/lat0, another point on the oblique


equator lon1/lat1, and scale or width

-Jo|O[c|C]lon0/lat0/lonp/latp/scale|width[+v]

Set projection center lon0/lat0, pole of oblique projection lonp/latp,


and scale or width

Give scale along oblique equator (with -Ja|b|c; 1:xxxx or plot-units/degree)


or width (with -JA|B|C; in plot-units). Use upper-case A|B|C to remove enforcement of a
northern hemisphere pole. Append +v to let the oblique Equator align with the y-axis [x-
axis]. Note: If the region (-R) is given without the +r modifier then the arguments are
considered oblique degrees relative to the projection center and not longitude/latitude
bounds.

-Jq|Q[lon0/[lat0/]]scale|width (Cylindrical Equidistant).

Give the central meridian lon0 (optional), standard parallel lat0 (optional), and
either scale (with -Jq; as 1:xxxx or plot-units/degree) or width (with -JQ; in plot-units)
The standard parallel is typically one of these (but can be any value):

 61.7 - Grafarend and Niermann, minimum linear distortion


 50.5 - Ronald Miller Equirectangular
 43.5 - Ronald Miller, minimum continental distortion
 42 - Grafarend and Niermann
 37.5 - Ronald Miller, minimum overall distortion
 0 - Plate Carree, Simple Cylindrical, Plain/Plane Chart

-Jt|Tlon0/[lat0/]scale|width (Transverse Mercator [C])


Give the central meridian lon0, central parallel lat0 (optional), and either scale (with -Jt;
as 1:xxxx or plot-units/degree) or width (with -JT; in plot-units).

-Ju|Uzone/scale|width (UTM - Universal Transverse Mercator [C]).

Give the UTM zone (A,B,1-60[C-X],Y,Z)) and either scale (with -Ju; as 1:xxxx or plot-
units/degree) or width (with -JU; in plot-units). Zones: If C-X not given, prepend - or + to
enforce southern or northern hemisphere conventions [default is northern if south > 0].

-Jy|Y[lon0/[lat0/]]scale|width (Cylindrical Equal-Area [E]).

Give the central meridian lon0 (optional), standard parallel lat0 (optional), and
either scale (with -Jy; as 1:xxxx or plot-units/degree) or width (with -JY; in plot-units).
The standard parallel is typically one of these (but can be any value):

 50 - Balthasart
 45 - Gall
 37.0666 - Caster
 37.4 - Trystan Edwards
 37.5 - Hobo-Dyer
 30 - Behrman
 0 - Lambert (default)

CONIC PROJECTIONS:

-Jb|Blon0/lat0/lat1/lat2/scale|width (Albers [E]).

Give projection center lon0/lat0, two standard parallels lat1/lat2, and


either scale (with -Jb; as 1:xxxx or plot-units/degree) or width (with -JB;
in plot-units).

-Jd|Dlon0/lat0/lat1/lat2/scale|width (Conic Equidistant)

Give projection center lon0/lat0, two standard parallels lat1/lat2, and


either scale (with -Jd; as 1:xxxx or plot-units/degree) or width (with -JD;
in plot-units).

-Jl|Llon0/lat0/lat1/lat2/scale|width (Lambert [C])


Give origin lon0/lat0, two standard parallels lat1/lat2, and scale along these
(with -Jl; as 1:xxxx or plot-units/degree) or width (with -JL; in plot-units).

-Jpoly|Poly/[lon0/[lat0/]]scale|width ((American) Polyconic).

Give the central meridian lon0 (optional), reference parallel lat0 (optional,
default = equator), and either scale along central meridian (with -Jpoly;
as 1:xxxx or plot-units/degree) or width (with -JPoly; in plot-units).

AZIMUTHAL PROJECTIONS:

Except for polar aspects, -Rw/e/s/n will be reset to -Rg. Use -


Rxlleft/ylleft/xuright/yuright+r for smaller regions.

-Ja|Alon0/lat0[/horizon]scale|width (Lambert [E]).

lon0/lat0 specifies the projection center. horizon specifies the max distance
from projection center (in degrees, <= 180, default 90). Give
either scale (with -Ja; as 1:xxxx or radius/lat, where radius is distance in plot-
units from origin to the oblique latitude lat) or width (with -JA; in plot-units).

-Je|Elon0/lat0[/horizon]scale|width (Azimuthal Equidistant).

lon0/lat0 specifies the projection center. horizon specifies the max distance
from projection center (in degrees, <= 180, default 180). Give scale (with -Je;
as 1:xxxx or radius/lat, where radius is distance in plot-units from origin to the
oblique latitude lat) or width (with -JE; in plot-units).

-Jf|Flon0/lat0[/horizon]scale|width (Gnomonic).

lon0/lat0 specifies the projection center. horizon specifies the max distance
from projection center (in degrees, < 90, default 60). Give scale (with -Jf;
as 1:xxxx or radius/lat, where radius is distance in plot-units from origin to the
oblique latitude lat) or width (with -JF; in plot-units).

-Jg|Glon0/lat0[/horizon]/scale|width (Orthographic).

lon0/lat0 specifies the projection center. horizon specifies the max distance
from projection center (in degrees, <= 90, default 90). Give scale (with -Jg;
as 1:xxxx or radius/lat, where radius is distance in plot-units from origin to the
oblique latitude lat.
-Jg|Glon0/lat0/altitude/azimuth/tilt/twist/Width/Height/scale|width (General
Perspective).

lon0/lat0 specifies the projection center. altitude is the height (in km) of the
viewpoint above local sea level. If altitude is less than 10, then it is the
distance from the center of the earth to the viewpoint in earth radii.
If altitude has a suffix r then it is the radius from the center of the earth in
kilometers. azimuth is measured to the east of north of view. tilt is the upward
tilt of the plane of projection. If tilt is negative, then the viewpoint is centered
on the horizon. Further, specify the clockwise twist, Width, and Height of the
viewpoint in degrees. Give scale (with -Jg; as 1:xxxx or radius/lat,
where radius is distance in plot-units from origin to the oblique latitude lat) or
width (with -JG; in plot-units).

-Js|Slon0/lat0[/horizon]/scale|width (General Stereographic [C]).

lon0/lat0 specifies the projection center. horizon specifies the max distance
from projection center (in degrees, < 180, default 90). Give scale (with -Js;
as 1:xxxx (true at pole) or lat0/1:xxxx (true at standard parallel lat)
or radius/lat (radius in plot-units from origin to the oblique latitude lat). Note
if 1:xxxx is used then to specify horizon you must also specify the lat as +-90
to avoid ambiguity.) or width (with -JS; in plot-units).

MISCELLANEOUS PROJECTIONS:

-Jh|H[lon0/]scale|width (Hammer [E]).

Give the central meridian lon0 (optional) and either scale along equator (with -
Jh; as 1:xxxx or plot-units/degree) or width (with -JH; in plot-units).

-Ji|I[lon0/]scale|width (Sinusoidal [E]).

Give the central meridian lon0 (optional) and either scale along equator (with -
Ji; as 1:xxxx or plot-units/degree) or width (with -JI; in plot-units).

-Jk|Kf[lon0/]scale|width (Eckert IV [E]).

Give the central meridian lon0 (optional) and either scale along equator (with -
Jk; as 1:xxxx or plot-units/degree) or width (with -JK; in plot-units).

-Jk|K[s][lon0/]scale|width (Eckert VI [E]).


Give the central meridian lon0 (optional) and either scale along equator (with -
Jk; as 1:xxxx or plot-units/degree) or width (with -JK; in plot-units).

-Jn|N[lon0/]scale|width (Robinson).

Give the central meridian lon0 (optional) and either scale along equator (with -
Jn; as 1:xxxx or plot-units/degree) or width (with -JN; in plot-units).

-Jr|R[lon0/]scale|width (Winkel Tripel).

Give the central meridian lon0 (optional) and either scale along equator (with -
Jr; as 1:xxxx or plot-units/degree) or width (with -JR; in plot-units).

-Jv|V[lon0/]scale|width (Van der Grinten).

Give the central meridian lon0 (optional) and either scale along equator (with -
Jv; as 1:xxxx or plot-units/degree) or width (with -JV; in plot-units).

-Jw|W[lon0/]scale|width (Mollweide [E]).

Give the central meridian lon0 (optional) and either scale along equator (with -
Jw; as 1:xxxx or plot-units/degree) or width (with -JW; in plot-units).

NON-GEOGRAPHICAL PROJECTIONS:

-Jp|Pscale|width[+a][+f[e|p|radius]][+kkind][+roffset][+torigin][+z[p|radius]]] (Polar
coordinates (theta, r))

Give scale (with -Jp; in plot-units/r-unit) or width (with -JP; in plot-units). The following
modifiers are supported by -Jp|P:

 +a to indicate that theta is azimuth CW from North instead of direction CCW from
East [Default is CCW from East].
 +f to flip the radial direction to point inwards, and append e to indicate
that r represents elevations in degrees (requires south >= 0 and north <=
90), p to select current planetary radius (determined by PROJ_ELLIPSOID) as
maximum radius [north], or radius to specify a custom radius.
 +k sets the annotation kind to be longitudes (x) or latitudes (y) [Default is
unspecified angles].
 +roffset to include a radial offset in measurement units [default is 0].
 +torigin in degrees so that this angular value is aligned with the positive x-axis (or
the azimuth to be aligned with the positive y-axis if +a) [default is 0].
 +z to annotate depth rather than radius [default is radius]. Alternatively, if
your r data are actually depths then you can append p or radius to get radial
annotations (r = radius - z) instead.

-Jx|Xx-scale|width[l|ppower|T|t][/y-scale|height[l|ppower|T|t]][d|g] (Linear, log, and


power scaling)

Give x-scale (with -Jx; as 1:xxxx or plot-units/x-unit) and/or y-scale (1:xxxx or plot-
units/y-unit); or specify width and/or height (with -JX; in plot-units). y-scale=x-scale if not
specified separately and using 1:xxxx implies that x-unit and y-unit are in meters. Use
negative scale(s) to reverse the direction of an axis (e.g., to have y be positive down).
Set height or width to 0 to have it recomputed based on the implied scale of the other
axis. Optionally, append to x-scale y-scale, width or height one of the following:

 d to indicate that data are geographical coordinates (in degrees).


 g to indicate that data are geographical coordinates
 l to take log10 of values before scaling.
 ppower to raise values to power before scaling.
 t to indicate that input coordinates are time relative to TIME_EPOCH.
 T to indicate that input coordinates are absolute time.

For mixed axes with only one geographic axis you may need to set -f as well.

When -J is used without any further arguments, or just with the projection type, the
arguments of the last used -J, or the last used -J with that projection type, will be used.

-Jz|Zparameters

Set z-axis scaling; same syntax as -Jx.


-Jproj|EPSG:n

Starting at GMT6 it is possible to use the PROJ library to do coordinate and


datum transforms. This is achieved via GDAL so it requires that GMT build is
linked to that library. It is, however, beyond the scope of this manual to document
the PROJ syntax (that is the syntax of the proj and cs2cs programs) so users
are referred to PROJ Applications for the details.
The usage of PROJ follows very closely the syntax of proj and cs2cs. The
projection parameters are encapsulated under the -J option. Because there are
normally several parameters defining a referencing system separated by spaces
(in PROJ or GDAL) we can either use double quotes as in -J“+proj=merc
+ellps=WGS84 +units=m” or just glue all parameters like in -
J+proj=merc+ellps=WGS84+units=m.

Using EPSG codes is also possible (but need the setting of


the GDAL_DATA environment variable to point to the GDAL’s data sub-
directory). For example -JEPSG:4326 sets the WGS-84 system.

For mapproject and grdproject we can go directly from the referencing system A
to B without the intermediate step of converting to geographic coordinates. That
is obtained (like in cs2cs) by using the +to keyword. Example: -
JEPSG:4326+to+proj=aeqd+ellps=WGS84+units=m. A much awaited bonus is
also that we now do not need to set -R to do point coordinate conversions.

While for point and grid conversions done by mapproject and grdproject we
can use all PROJ projections, the situations is, however, rather more limited for
mapping purposes. Here, only the subset of the PROJ projections that can be
mapped into the GMT projections syntax is available to use. Another aspect that
is not present in PROJ, because it’s not a mapping library, is how to set the map
scale or map dimension. We introduced the two
extensions +width=size and +scale=1:xxxx that work exactly like the map
width and scale in classical GMT. It is also allowed to provide the scale (but NOT
the width) by appending the string “/1:xxx” to the end of the projection
parameters.

The -R option

Syntax

-Rxmin/xmax/ymin/ymax[+r][+uunit]

Specify the region of interest. (See cookbook information).

Description
The -R option defines the map region or data domain of interest. It may be specified in
one of seven ways (options 1 and 2 are shown in panels a) and b) respectively of the
Figure Map region):

1. -Rxmin/xmax/ymin/ymax[+uunit]. This is the standard way to specify Cartesian data


domains and geographic regions when using map projections where meridians and
parallels are rectilinear. Optionally, append +uunit to specify a region in projected
units (e.g., UTM meters) where xmin/xmax/ymin/ymax are Cartesian projected
coordinates compatible with the chosen projection and unit is an allowable distance
unit.
2. -Rxlleft/ylleft/xuright/yuright+r. This form is useful for map projections that are
oblique, making meridians and parallels poor choices for map boundaries. Here, we
instead specify the lower left corner and upper right corner geographic coordinates,
followed by the modifier +r. This form guarantees a rectangular map even though
lines of equal longitude and latitude are not straight lines.
3. -Rg or -Rd. These forms can be used to quickly specify the global domain (0/360
for -Rg and -180/+180 for -Rd in longitude, with -90/+90 in latitude).
4. -Rgridfile. This will copy the domain settings found for the grid in specified file. Note
that depending on the nature of the calling module, this mechanism will also set grid
spacing and possibly the grid registration (see Grid registration: The -r option).
5. -Rcode1,code2,…[+e|r|Rincs]]. This indirectly supplies the region by consulting the
DCW (Digital Chart of the World) database and derives the bounding regions for one
or more countries given by the codes. Simply append one or more comma-
separated countries using the two-character ISO 3166-1 alpha-2 convention. To
select a state within a country (if available), append .state, e.g, US.TX for Texas. To
specify a whole continent, prepend = to any of the continent
codes AF (Africa), AN (Antarctica), AS (Asia), EU (Europe), OC (Oceania), NA (Nort
h America), or SA (South America). The following modifiers can be appended:
 +r to adjust the region boundaries to be multiples of the steps indicated
by inc, xinc/yinc, or winc/einc/sinc/ninc [default is no adjustment]. For example, -
RFR+r1 will select the national bounding box of France rounded to nearest
integer degree.
 +R to extend the region outward by adding the amounts specified
by inc, xinc/yinc, or winc/einc/sinc/ninc [default is no extension].
 +e to adjust the region boundaries to be multiples of the steps indicated
by inc, xinc/yinc, or winc/einc/sinc/ninc, while ensuring that the bounding box
extends by at least 0.25 times the increment [default is no adjustment].
6. -Rjustifyx0/y0/nx/ny, where justify is a 2-character combination of L|C|R (for left,
center, or right) and T|M|B (for top, middle, or bottom) (e.g., BL for lower left). The
two character code justify indicates which point on a rectangular grid region
the x0/y0 coordinates refer to and the grid dimensions nx and ny are used with grid
spacings given via -I to create the corresponding region. This method can be used
when creating grids. For example, -RCM25/25/50/50 specifies a 50x50 grid centered
on 25,25.
7. -Rxmin/xmax/ymin/ymax/zmin/zmax. This method can be used for perspective views
with the -Jz and the -p option, where the z-range (zmin/zmax) is appended to the
first method to indicate the third dimension. This is not used for -p without -Jz, in
which case a perspective view of the place is plotted with no third dimension
In case of perspective view -p, a z-range (zmin, zmax) can be appended to indicate the
third dimension. This needs to be done only when using the -Jz option, not when using
only the -p option. In the latter case a perspective view of the plane is plotted, with no
third dimension.

The -U option

Syntax

-U[label|+c][+jjust][+odx/dy]

Draw GMT time stamp logo on plot. (See cookbook information).

Description

The -U option draws the GMT system time stamp on the plot. The following modifiers
are supported:

 label to append the text string given in label (which must be surrounded by double
quotes if it contains spaces).
 +c to plot the current command string.
 +jjustify to specify the justification of the time stamp, where justify is a two-
character justification code that is a combination of a horizontal (L(eft), C(enter),
or R(ight)) and a vertical (T(op), M(iddle), or B(ottom)) code [default is BL].
 +odx[/dy] to offset the anchor point for the time stamp by dx and optionally dy (if
different than dx).
The GMT
parameters MAP_LOGO, MAP_LOGO_POS, FONT_LOGO and FORMAT_TIME_STA
MP can affect the appearance; see the gmt.conf man page for details. The time string
will be in the locale set by the environment variable TZ (generally local time).

The -V option

Syntax

-V[level]

Select verbosity level [w]. (See cookbook information).

Description

The -V option controls the verbosity mode, which determines which messages are sent
to standard error. Choose among 7 levels of verbosity; each level adds more messages:

 q - Quiet, not even fatal error messages are produced.


 e - Error messages only.
 w - Warnings.
 t - Timings (report runtimes for time-intensive algorithms).
 i - Informational messages (same as -V only).
 c - Compatibility warnings (if compiled with backward-compatibility).
 d - Debugging messages.
This option can also be set by specifying the
default GMT_VERBOSE as quiet, error, warning, timing, compat, information,
or debug, in order of increased verbosity [default is warning].

The -X -Y options

Syntax
-X[a|c|f|r][xshift]

Shift plot origin. (See cookbook information).


-Y[a|c|f|r][yshift]

Shift plot origin. (See cookbook information).

Description

The -X and -Y options shift the plot origin relative to the current origin by (xshift,yshift).
Optionally, append the length unit (c, i, or p). Default is
(MAP_ORIGIN_X, MAP_ORIGIN_Y) for new plots, which ensures that boundary
annotations fit on the page. Subsequent overlays will be co-registered with the previous
plot unless the origin is shifted using these options. The following modifiers are
supported [default is r]:

 Prepend a to shift the origin back to the original position after plotting.
 Prepend c to center the plot on the center of the paper (optionally add a shift).
 Prepend f to shift the origin relative to the fixed lower left.
 Prepend r to move the origin relative to its current location.
When -X or -Y are used without any further arguments, the values from the last use of
that option in a previous GMT command will be used. Note that -X and -Y can also
access the previous plot bounding box dimensions w and h and construct offsets that
involves them. For instance, to move the origin up 2 cm beyond the height of the
previous plot, use -Yh+2c. To move the origin half the width to the right, use -Xw/2.

The -a option

Syntax

-a[[col=]name][,…]

Control how aspatial data are handled in GMT during input and output.

Description

GMT relies on external tools to translate geospatial files such as shapefiles into a format
we can read. The tool ogr2ogr in the GDAL package can do such translations and
preserve the aspatial metadata via a new OGR/GMT format specification (See the
cookbook chapter The GMT Vector Data Format for OGR Compatibility). For this to be
useful we need a mechanism to associate certain metadata values with required input
and output columns expected by GMT programs. The -a option allows you to supply
one or more comma-separated associations col=name, where name is the name of an
aspatial attribute field in a OGR/GMT file and whose value we wish to as data input for
column col. The given aspatial field thus replaces any other value already set. Note: col
= 0 is the first data column. Note: If no aspatial attributes are needed then the -a option
is not needed – GMT will still process and read such data files.

OGR/GMT input with -a option

If you need to populate GMT data columns with (constant) values specified by aspatial
attributes, use -a and append any number of comma-separated col=name associations.
For example, -a2=depth will read the spatial x,y columns from the file and add a third (z)
column based on the value of the aspatial field called depth. You can also associate
aspatial fields with other settings such as labels, fill colors, pens, and values (for
looking-up colors) by letting the col value be one
of D (for distance), G (for fill), I (for ID), L (for label), T (for text), W (for pen),
or Z (for value). This works analogously to how standard multi-segment files can pass
such options via its segment headers (See the cookbook chapter GMT File
Formats). Note: If the leading col= is omitted, the column value is automatically
incremented starting at 2.

OGR/GMT output with -a option

GMT table-writing tools can also output the OGR/GMT format directly. Specify if certain
GMT data columns with constant values should be stored as aspatial metadata
using col=name[:type], where you can optionally specify what data type it should be
from the options double, float, integer, char, string, logical, byte, or datetime [default
is double]. As for input, you can also use the special col entries
of D (for distance), G (for fill), I (for ID), L (for label), T (for text), W (for pen),
or Z (for value) to have values stored as options in segment headers be used as the
source for the named aspatial field. The type will be set automatically for these
special col entries. Finally, for output you must append +ggeometry,
where geometry can be any of [M]POINT|LINE|POLY; where M represents the multi-
versions of these three geometries. Use upper-case +G to signal that you want to split
any line or polygon features that straddle the Dateline.

The -bi option

Syntax

-bi[ncols][type][w][+l|b]

Select native binary format for primary input (secondary inputs are always
ASCII).

Description

Select native binary format for primary input, where ncols is the number of data columns
of given type and type must be one of:

 c - int8_t (1-byte signed char)


 u - uint8_t (1-byte unsigned char)
 h - int16_t (2-byte signed int)
 H - uint16_t (2-byte unsigned int)
 i - int32_t (4-byte signed int)
 I - uint32_t (4-byte unsigned int)
 l - int64_t (8-byte signed int)
 L - uint64_t (8-byte unsigned int)
 f - 4-byte single-precision float
 d - 8-byte double-precision float
 x - use to skip ncols anywhere in the record

For records with mixed types, simply append additional comma-separated combinations
of ncols type (no space). The following modifiers are supported:

 w after any item to force byte-swapping


 +l|b to indicate that the entire data file should be read as little- or big-endian,
respectively.

The cumulative number of ncols may exceed the columns actually needed by the
program. If ncols is not specified we assume that type applies to all columns and
that ncols is implied by the expectation of the program. When using native binary data
the user must be aware of the fact that GMT has no way of determining the actual
number of columns in the file. Native binary files may have a header section, where
the -h option can be used to skip the first n bytes. If the input file is netCDF, no -b is
needed; simply append ?var1/var2/… to the filename to specify the variables to be read
(see GMT File Formats and Modifiers for COARDS-compliant netCDF files for more
information).

The -bo option

Syntax

-bo[ncols][type][w][+l|b]

Select native binary output.

Description

Select native binary output, where ncols is the number of data columns of type, which
must be one of c, u, h, H, i, I, l, L, f, or d (see -bi types for descriptions). For a mixed-
type output record, append additional comma-separated combinations of ncols type (no
space). The following modifiers are supported:

 w after any item to force byte-swapping


 +l|b to indicate that the entire data file should be read as little- or big-endian,
respectively.

If ncols is not specified we assume that type applies to all columns and that ncols is
implied by the default output of the program. Note: NetCDF file output is not supported.

The -c option

Syntax

-c[row,col|index]

Advance to the selected subplot panel.


Description

The -c option can be used to either advance the focus of plotting to the next panel in the
sequence (either by row or by column as set by subplot’s -A option) or to specify directly
the row,col or 1-D index of the desired panel, when using subplot to assemble multiple
individual panels in a matrix layout. The -c option is only allowed when in subplot mode.
If no -c option is given for the first subplot then we default to row=col=index=0, i.e., the
upper left panel. Note: row, col, and index all start at 0.

The -d option

Syntax

-di|onodata

Substitute specific values with NaN.

Description

The -d option allows user-coded missing data values to be translated to official NaN
values in GMT. Within GMT, any missing values are represented by the IEEE NaN
value. However, user data may occasionally denote missing data with an unlikely value
(e.g., -99999). Since GMT cannot guess this special missing data value, you can use
the -d option to have such values replaced with NaNs. Similarly, the -d option can
replace all NaNs with the chosed nodata value should the GMT output need to conform
to such a requirement.

For input only, use -dinodata to examine all input columns. If any item equals nodata,
the value is interpreted as a missing data item and is substituted with the value NaN.

For output only, use -donodata to examine all output columns. If any item equals NaN,
the NaN value is substituted with the chosen missing data value nodata.

The -e option

Syntax
-e[~]“pattern” | -e[~]/regexp/[i]

Only accept ASCII data records that contain the specified pattern.

Description

The -e option offers a built-in pattern scanner that will only pass records that match the
given pattern or regular expressions, whereas modules that read ASCII tables will
normally process all the data records that are read. The test can also be inverted to only
pass data records that do not match the pattern, by using -e~. The test is not applied to
header or segment headers. Should your pattern happen to start with ~ you will need to
escape this character with a backslash [Default accepts all data records]. For matching
data records against extended regular expressions, please enclose the expression in
slashes. Append i for case-insensitive matching. To supply a list of such patterns,
give +ffile with one pattern per line. To give a single pattern starting with +f, escape it
with a backslash.

The -f option

Syntax

-f[i|o]colinfo

Specify the data types of input and/or output columns (time or geographical
data).

Description

The -f option specifies what kind of data each input or output column contains when
map projections are not required. Optionally, append i or o to make this apply only to
input or output, respectively [Default applies to both]. Append a text string with
information about each column (or range of columns) separated by commas. Each
string starts with the column number (0 is the first column) followed by
either x (longitude), y (latitude), T (absolute calendar time) or t (relative time in
chosen TIME_UNIT since TIME_EPOCH). If several consecutive columns have the
same format you may specify a range of columns rather than a single column. Column
ranges must be given in the format start[:inc]:stop, where inc defaults to 1 if not
specified. For example, if our input file has geographic coordinates (latitude, longitude)
with absolute calendar coordinates in the columns 3 and 4, we would
specify fi0y,1x,3:4T. All other columns are assumed to have the default (floating point)
format and need not be set individually.

The shorthand -f[i|o]g means -f[i|o]0x,1y (i.e., geographic coordinates). A special use
of -f is to select -fp[unit], which requires -J and lets you use projected map coordinates
(e.g., UTM meters) as data input. Such coordinates are automatically inverted to
longitude, latitude during the data import. Optionally, append a length unit (see
table distance units) [default is meter]. For more information, see Sections Input data
formats and Output data formats.

The -g option

Syntax

-g[a]x|y|d|X|Y|D|[col]zgap[+n|p]

Examine the spacing between consecutive data points in order to impose breaks
in the line.

Description

The -g option is used to detect gaps based on one or more criteria. Repeat the option to
specify multiple criteria and prepend a to subsequent modifiers to specify that all the
criteria must be met [default imposes breaks if any one criteria is met]. The criteria is
specified using the x|y|d|X|Y|D|[col]z modifiers. The upper-case options specify that the
criteria should be applied to the projected coordinates for modules that map data to map
coordinates.

 x|X - define a gap when there is a large enough change in the x coordinates (upper
case to use projected coordinates).
 y|Y - define a gap when there is a large enough change in the y coordinates (upper
case to use projected coordinates).
 d|D - define a gap when there is a large enough distance between coordinates
(upper case to use projected coordinates).
 [col]z - define a gap when there is a large enough change in the data in
column col [default col is 2 (i.e., 3rd column)].
A unit u may be appended to the specified gap:

 For geographic data (x|y|d), the unit may be arc d(egree), m(inute), and s(econd), or
(m)e(ter), f(eet), k(ilometer), M(iles), or n(autical miles) [Default is (m)e(ter)].
 For projected data (X|Y|D), the unit may be i(nch), c(entimeter), or p(oint) [Default
unit is set by PROJ_LENGTH_UNIT].
One of the following modifiers can be appended to gap [default imposes breaks based
on the absolute value of the difference between the current and previous value]:

 +n - specify that the previous value minus the current column value must
exceed gap for a break to be imposed.
 +p - specify that the current value minus the previous value must exceed gap for a
break to be imposed.
Note: For x|y|z with time data the unit is instead controlled by TIME_UNIT. Note: GMT
has other mechanisms that can determine line segmentation, including segments
defined by multiple segment header records (see the cookbook chapter GMT File
Formats) or segments defined by NaN values when IO_NAN_RECORDS is set
to pass [default skips NaN values].

The -h option

Syntax

-h[i|o][n][+c][+d][+msegheader][+rremark][+ttitle]

Specify that input and/or output file(s) have n header records [default is 0].

Description

Specify that the primary input file(s) has n header record(s). The default number of
header records is set by IO_N_HEADER_RECS [default is 0]. Use -hi if only the
primary input data should have header records [Default will write out header records if
the input data have them]. For output you may control the writing of header records
using -h[o] and the optional modifiers:

 +d to remove existing header records.


 +c to add a header comment with column names to the output [default is no column
names].
 +m to add a segment header segheader to the output after the header block [default
is no segment header].
 +r to add a remark comment to the output [default is no comment].
The remark string may contain \n to indicate line-breaks.
 +t to add a title comment to the output [default is no title]. The title string may contain
\n to indicate line-breaks.
Note: Blank lines and lines starting with # are always skipped. To use another leading
character for indicating header records, set IO_HEADER_MARKER. With -h in effect
the first n records are taken verbatim as headers and not skipped even if any is starting
with #. Note: If used with native binary data (using -b) we interpret n to instead mean
the number of bytes to skip on input or pad on output.

The -i option

Syntax

-icols[+l][+ddivisor][+sscale][+ooffset][,…][,t[word]]

Select specific data columns for primary input, in arbitrary order.

Description

The -i option allows you to specify which input file physical data columns to use and in
what order. Specify individual columns or column ranges in the format start[:inc]:stop,
where inc defaults to 1 if not specified, separated by commas [Default reads all columns
in order, starting with the first column (i.e., column 0)]. Columns can be repeated. The
chosen data columns will be used as given and columns not listed will be skipped.
Optionally, append one of the following modifiers to any column or column range to
transform the input columns:

 +l to take the log10 of the input values.


 +d to divide the input values by the factor divisor [default is 1].
 +s to multiply the input values by the factor scale [default is 1].
 +o to add the given offset to the input values [default is 0].
To read from a given column until the end of the record, leave off stop when specifying
the column range. Normally, any trailing text is read but when -i is used you must
explicitly add the column t to retain the text. To only ingest a single word from the
trailing text, append the word number (first word is 0). Finally, -in will simply read the
numerical input and skip any trailing text.

The -j option (spherical distance calculations)

Syntax

-je|f|g

Determine how spherical distances are calculated in modules that support this
[Default is -jg].

Description

GMT has different ways to compute distances on planetary bodies:

 -jg to perform great circle distance calculations, with parameters such as distance
increments or radii compared against calculated great circle distances [Default is -
jg].
 -jf to select Flat Earth mode, which gives a more approximate but faster result.
 -je to select ellipsoidal (or geodesic) mode for the highest precision and slowest
calculation time.
Note: All spherical distance calculations depend on the current ellipsoid
(PROJ_ELLIPSOID), the definition of the mean radius (PROJ_MEAN_RADIUS), and
the specification of latitude type (PROJ_AUX_LATITUDE). Geodesic distance
calculations is also controlled by method (PROJ_GEODESIC).

The -l option

Syntax

-l[label][+Dpen][+Ggap][+Hheader][+L[code/]text][+Ncols][+Ssize[/height]][+V[pen]]
[+ffont][+gfill][+jjustify][+ooff][+ppen][+sscale][+wwidth]
Add a map legend entry to the session legend information file for the current plot.

Description

The -l option is used to automatically build the specfile that is read by


the legend module to create map or plot legends. This allows detailed and complicated
legends that mix a variety of items, such as symbols, free text, colorbars, scales,
images, and more. Yet, a simple legend will suffice for the vast majority of plots
displaying symbols or lines. Optionally, append a text label to describe the entry. The
following modifiers are supported to allow further changes to the legend that is built
by legend (upper-case modifiers reflect legend codes described in legend, which
provides more details and customization):

 +D to draw a horizontal line in the given pen before the legend entry is placed
[default is no line].
 +G to add the vertical space specified by gap [default is no extra space].
 +H to add the specified legend header [default is no header].
 +L to set a line text. Optionally, prepend a horizontal justification
code L(eft), C(enter), or R(ight) for text [default is C].
 +N to change the number of columns used to set the following legend items
to cols [default is 1].
 +S to override the size of the current symbol for the legend or set a height if plotting
a line or contour [default uses the same symbol as plotted].
 +V to start and +vpen to stop drawing vertical line from previous to current horizontal
line [default is no vertical line].
 +f to set the font used for the legend header [default is FONT_TITLE].
 +g to set the fill used for the legend frame [default is white].
 +j to set placement of the legend using the two-character justification
code justify [default is TR].
 +o to set the offset from legend frame to anchor point [default is 0.2c].
 +p to set the pen used for the legend frame [default is 1p].
 +s to resize all symbol and length sizes in the legend by scale [default is no scaling].
 +w to set legend frame width [default is auto].
Note: Default pen is given by MAP_DEFAULT_PEN. Note: +H, +g, +j, +o, +p, +w,
and +s will only take effect if appended to the very first -l option for a plot.
The +N modifier, if appended to the first -l option, affects the legend width (unless set
via +w); otherwise it just subdivides the available width among the specified columns.
If legend is not called explicitly we will call it implicitly when finishing the plot
via end. Note: If auto-coloring is used for pens or fills and -l is set then label may
contain a C-format for integers (e.g., %3.3d) or just # and we will use the sequence
number with the format to build the label entries. Alternatively, give a list of comma-
separated labels, or give no label if your segment headers contain label settings.

The -n option

Syntax

-n[b|c|l|n][+a][+bg|p|n][+c][+tthreshold]

Select grid interpolation mode.

Description

The -n option controls parameters used for 2-D grids resampling [default is bicubic
interpolation with antialiasing and a threshold of 0.5, using geographic (if grid is known
to be geographic) or natural boundary conditions]. Append one of the following to select
the type of spline used:

 b to use B-spline smoothing.


 c to use bicubic interpolation.
 l to use bilinear interpolation.
 n to use nearest-neighbor value (for example to plot categorical data).
The following modifiers are supported:

 +a to switch off antialiasing (where supported) [default uses antialiasing].


 +b to override boundary conditions used, by appending g for geographic, p for
periodic, or n for natural boundary conditions. For the latter two you may
append x or y to specify just one direction, otherwise both are assumed.
 +c to clip the interpolated grid to input z-min/z-max [default may exceed limits].
 +t to control how close to nodes with NaNs the interpolation will go based
on threshold. A threshold of 1.0 requires all (4 or 16) nodes involved in interpolation
to be non-NaN. For example, 0.5 will interpolate about half way from a non-NaN
value and 0.1 will go about 90% of the way [default is 0.5].
The -o option

Syntax

-ocols[,…][,t[word]]

Select specific data columns for primary output, in arbitrary order.

Description

The -o option allows you to specify which output file physical data columns to use and in
what order. Specify individual columns or column ranges in the format start[:inc]:stop,
where inc defaults to 1 if not specified, separated by commas [Default writes all columns
in order, starting with the first column (i.e., column 0)]. Columns can be repeated. The
chosen data columns will be used as given and columns not listed will be skipped. To
write from a given column until the end of the record, leave off stop when specifying the
column range.

Normally, any trailing text in the internal records will be written but when -o is used you
must explicitly add the column t. To only output a single word from the trailing text,
append the word number (first word is 0). Finally, -on will simply write the numerical
output only and skip any trailing text, while -ot will only output the trailing text (or
selected word). Note: If -i is also used then columns given to -o correspond to the
order after the -i selection and not the columns in the original record.

The -p option

Syntax

-p[x|y|z]azim[/elev[/zlevel]][+wlon0/lat0[/z0]][+vx0/y0]

Select perspective view and set the azimuth and elevation of the viewpoint.

Description

All plotting programs that normally produce a flat, two-dimensional illustration can be
told to view this flat illustration from a particular vantage point, resulting in a perspective
view. You can select perspective view with the -p option by setting the azimuth (azim) of
the viewpoint [Default is 180]. The following modifiers are supported:

 x|y|z to plot against the “wall” x = level (using x) or y = level (using y) or the
horizontal plain (using z) [default is z].
 /elev to set the elevation of the viewport [Default is 90].
 /zlevel to indicate the z-level at which all 2D material, like the plot frame, is plotted
(only valid when -p is used in consort with -Jz or -JZ) [Default is at the bottom of the
z-axis].
For frames used for animation, we fix the center of your data domain. Specify another
center using one of the following modifiers:

 +w to project lon0/lat0 (and z0 if applicable) to the center of the page size.


 +v to specify the coordinates of the projected 2-D view point as x0/y0.
When -p is used without any further arguments, the values from the last use of -p in a
previous GMT command will be used (in modern mode this also supplies the previous -
Jz or -JZ if doing a 3-D region). Alternatively, you can perform a simple rotation about
the z-axis by just giving the rotation angle. Optionally, use +v or +w to select another
axis location than the plot origin.

The -q option

Syntax

-q[i|o][~]rows[+ccol][+a|f|s]

Select specific data rows to be read and/or written.

Description

The -q option is used to select specific data rows to be read (using -q or -qi) or written
(using -qo) [Default is all rows]. Specify individual rows or row ranges in the
format start[:inc]:stop, where inc defaults to 1 if not specified, separated by commas
[Default reads and writes all rows in order, starting with the first row (i.e., row 0)]. To
read (or write) from a given row until the end of the data, leave off stop. To select all the
rows not specified by the given ranges, prepend the selected rows with a leading ~.
Append one of the following modifiers to control how the rows are counted [Default
is +a]:

 +a to count all rows in the data set.


 +f to reset the count at the start of each file.
 +s to reset the count at the start of each segment.
Alternatively, use +ccol to indicate that the arguments instead are min/max data
limits for the values in column col. With +ccol, only rows whose data for the given
column col are within the range(s) given by the min/max limits are read (with -qi) or
written (with -qo). Note: Because arguments may contain colons or be negative, your
must specify start/stop instead of start[:inc]:stop.

Note: Header records do not increase the row counters; only data records do.

The -r option (grid registration)

Syntax

-r[g|p]

Select gridline or pixel node registration.

Description

All 2-D grids in GMT have their nodes organized in one of two ways, known
as gridline and pixel registration. The GMT default is gridline registration (-rg); programs
that allow for the creation of grids can use the -r option (or -rp) to select pixel
registration instead.

Most observed data tend to be in gridline registration while processed data sometime
may be distributed in pixel registration. While you may convert between the two
registrations this conversion looses the Nyquist frequency and dampens the other high
frequencies. It is best to avoid any registration conversion if you can help it. Planning
ahead may be important. (Node registrations are defined in Section Grid registration:
The -r option of the GMT Technical Reference and Cookbook.)

The -s option
Syntax

-s[cols][+a][+r]

Suppress output of data records whose z-value(s) equal NaN.

Description

The -s option can be used to suppress output for records whose z-value equals NaN
[default outputs all records]. Optionally, supply a comma-separated list of all columns or
column ranges to consider for this NaN test [default only considers the third data
column (i.e., cols = 2)]. Column ranges must be given in the format start[:inc]:stop,
where inc defaults to 1 if not specified. The following modifiers are supported:

 +r to reverse the suppression, i.e., only output the records whose z-value equals
NaN.
 +a to suppress the output of the record if just one or more of the columns equal NaN
[default skips record only if values in all specified cols equal NaN]
The -t option

Syntax

-ttransp[/transp2][+f|s]

Set transparency level(s) for an overlay.

Description

The -t option allows you to change the transparency level for the current overlay by
appending the transp percentage in the 0-100 range [default is 0 (i.e., opaque)].
Normally, transp applies to both fill and stroke, but you can limit the transparency to one
of them by appending +f or +s for fill or stroke, respectively. Alternatively,
append /transp2 to set separate transparencies for fills and strokes.

Transparency may also be controlled on a feature by feature basis when setting color or
fill (see the cookbook section Specifying area fill attributes). Note: The
modules plot, plot3d, and text can all change transparency on a record-by-record basis
if -t is given without argument and the input file supplies variable transparencies as the
last numerical column value(s). Note: The transparency is only visible when PDF or
raster format output is selected because the PostScript language does not support
transparency. Only the PNG format selection adds a transparency layer in the image
(for further processing).

The -w option

Syntax

-wy|a|w|d|h|m|s|cperiod[/phase][+ccol]

Convert input records to a cyclical coordinate.

Description

The -w option converts the input x-coordinate to a cyclical coordinate, or a different


input column if selected via the +c modifier. Temporal data (i.e., regular time series) can
be analyzed for periods via standard spectral analysis, such as offered
by spectrum1d and grdfft. However, it is often of interest to examine aspects of such
periodicities in the time domain. To enable such analyses we need to convert our
monotonically increasing time coordinates to periodic or cyclic coordinates so that data
from many cycles can be stacked, binned, displayed in histograms, etc. The conversion
from input x, y, or z coordinates to wrapped, periodic coordinates follows the simple
equation

t′=(t−τ)modT,𝑡′=(𝑡−𝜏)mod𝑇,
where t is the input coordinate, τ𝜏 is a phase-shift (typically zero), and T is the desired
period for the modulus operator, yielding cyclic coordinates t′𝑡′. GMT offers many
standard time cycles in prescribed units plus a custom cycle for other types of Cartesian
coordinates. The table below shows the values for units, phase and period that are
prescribed and only requires the user to specify the corresponding wrapping code (y|a|
w|d|h|m|s|cperiod):
Cod
Purpose (unit) Period Phase Range
e

y Yearly cycle (normalized) 1 year 0 0–1


Cod
Purpose (unit) Period Phase Range
e

a Annual cycle (month) 1 year 0 0–12

w Weekly cycle (day) 1 week 0 0–7

d Daily cycle (hour) 1 day 0 0–24

h Hourly cycle (minute) 1 hour 0 0–60

m Minute cycle (second) 1 minute 0 0–60

s Second cycle (second) 1 second 0 0–1

c Custom cycle (normalized) T𝑇 τ𝜏 0–1

Optionally, append +ccol to select the input column with the coordinates to be wrapped,
[default col is 0 (i.e., the first column)]. If the custom cycle c is chosen then you must
also supply the period and optionally any phase [default is 0] in the same units of your
data (i.e., no units should be appended to -w).

Note: Coordinates for w in the range 0-1 correspond to the first day of the week
[Monday] but can be changed via TIME_WEEK_START. Note: If a temporal cycle is
indicated then we implicitly set -f to indicate absolute time (unless already set
separately). See the cookbook section Examining data cycles: The -w option for
examples.

The -x option

Syntax

-x[[-]n]

Specify the number of active cores to be used in any OpenMP-enabled multi-


threaded algorithms.

Description

The -x option limits the number of cores to be used in any OpenMP-enabled multi-
threaded algorithms [default is to use all available cores]. Append n to only use n cores
(if too large it will be truncated to the maximum cores available). Finally, give a
negative n to select (all - n) cores (or at least 1 if n equals or exceeds all). The -x option
is only available to GMT modules compiled with OpenMP support, with the exception
of movie and batch which handle their own parallel execution.

The -: option

Syntax

-:[i|o]

Swap 1st and 2nd column on input and/or output.

Description The -: option swaps the 1st and 2nd column on input and output [default is
no swapping]. Append i to select input only or o to select output only [default affects
both]. This option is typically used to handle (latitude, longitude) files; see also Input
columns selection: The -i option. Note that command line arguments that may take
geographic coordinates (e.g., -R) always expect longitude before latitude. Also,
geographical grids are expected to have the longitude as first (minor) dimension.

Module help and configuration


-^ or just -

Print a short message about the syntax of the command, then exit (NOTE: on
Windows just use -).
-+ or just +

Print an extensive usage (help) message, including the explanation of any


module-specific option (but not the GMT common options), then exit.
-? or no arguments

Print a complete usage (help) message, including the explanation of all options,
then exit.
--PAR=value

Temporarily override a GMT default setting; repeatable. See gmt.conf for


parameters.

Specifying Color
color

The color of lines, areas and patterns can be specified by a valid color name, by
a gray shade (in the range 0-255), by a decimal color triplet RGB (r/g/b, each in
the range 0–255), by hue-saturation-value HSV (h-s-v, with ranges of 0-360, 0-1,
0-1), by cyan/magenta/yellow/black CMYK (c/m/y/k, each in the range 0-1), or by
a hexadecimal color code (#rrggbb, as used in HTML). For a transparency effect,
append @transparency in the 0–100 percent range [Default is 0 (opaque)] Note:
Transparency effects are only visible when PDF or a raster graphics format is
selected. See Explanation of color codes in GMT for more information and a full
list of color names.

Specifying Fill
fill

The attribute fill specifies the solid shade or solid color (see Specifying
Color above) or the pattern used for filling polygons. Patterns are specified
as ppattern, where pattern set the number of the built-in pattern (1-90) or the
name of a raster image file. The optional +rdpi sets the resolution of the image
[300]. For 1-bit rasters: use upper case P for inverse video, or
append +fcolor and/or +bcolor to specify fore- and background colors
(no color given means transparency). See Predefined Bit and Hachure Patterns
in GMT for information on individual built-in patterns.

Specifying Fonts
font

The attributes of text fonts as defined by font is a comma delimited list


of size, fonttype and fill, each of which is optional. size is the font size (usually in
points) but c or i can be added to indicate other units. fonttype is the name (case
sensitive!) of the font or its equivalent numerical ID (e.g., Helvetica-Bold or
1). fill specifies the gray shade, color or pattern of the text (see Specifying
Fill above). Optionally, you may append =pen to the fill value in order to draw a
text outline. If you want to avoid that the outline partially obscures the text,
append =~pen instead; in that case only half the linewidth is plotted on the
outside of the font only. If an outline is requested, you may optionally skip the
text fill by setting it to -, in which case the full pen width is always used. If any of
the font attributes is omitted their default or previous setting will be retained.

The 35 available fonts (plus 4 optional Japanese fonts) are:

1. Helvetica
2. Helvetica-Bold
3. Helvetica-Oblique
4. Helvetica-BoldOblique
5. Times-Roman
6. Times-Bold
7. Times-Italic
8. Times-BoldItalic
9. Courier
10. Courier-Bold
11. Courier-Oblique
12. Courier-BoldOblique
13. Symbol
14. AvantGarde-Book
15. AvantGarde-BookOblique
16. AvantGarde-Demi
17. AvantGarde-DemiOblique
18. Bookman-Demi
19. Bookman-DemiItalic
20. Bookman-Light
21. Bookman-LightItalic
22. Helvetica-Narrow
23. Helvetica-Narrow-Bold
24. Helvetica-Narrow-Oblique
25. Helvetica-Narrow-BoldOblique
26. NewCenturySchlbk-Roman
27. NewCenturySchlbk-Italic
28. NewCenturySchlbk-Bold
29. NewCenturySchlbk-BoldItalic
30. Palatino-Roman
31. Palatino-Italic
32. Palatino-Bold
33. Palatino-BoldItalic
34. ZapfChancery-MediumItalic
35. ZapfDingbats
36. Ryumin-Light-EUC-H
37. Ryumin-Light-EUC-V
38. GothicBBB-Medium-EUC-H
39. GothicBBB-Medium-EUC-V
Specifying Pens
pen

The attributes of lines and symbol outlines as defined by pen is a comma-


delimited list of width, color and style, each of which is optional. width can be
indicated as a measure (in points (this is the default), centimeters, or inches) or
as faint, default, thin[ner|nest], thick[er|est], fat[ter|test],
or wide. color specifies a gray shade or color (see Specifying
Color above). style can be any of ‘solid’, ‘dashed’ ‘dotted’, ‘dashdot’, or ‘dotdash’,
or a custom combination of dashes ‘-‘ and dots ‘.’. If any of the attributes is
omitted their default or previous setting will be retained. See GMT Cookbook &
Technical Reference Specifying pen attributes for more information.

ASCII Format Precision


The ASCII output formats of numerical data are controlled by parameters in
your gmt.conf file. Longitude and latitude are formatted according
to FORMAT_GEO_OUT, absolute time is under the control
of FORMAT_DATE_OUT and FORMAT_CLOCK_OUT, whereas general floating point
values are formatted according to FORMAT_FLOAT_OUT. Be aware that the format in
effect can lead to loss of precision in ASCII output, which can lead to various problems
downstream. If you find the output is not written with enough precision, consider
switching to binary output (-bo if available) or specify more decimals using
the FORMAT_FLOAT_OUT setting.

Grid File Formats


By default GMT writes out grids as single precision floats in a COARDS-complaint
netCDF file format. However, GMT is able to produce and read grid files in many other
commonly used grid file formats and also facilitates so called “packing” of grids, writing
out floating point data as 1- or 2-byte integers. To specify the precision, scale and
offset, the user should add the suffix [=id][+sscale][+ooffset][+ninvalid], where id is a
two-letter identifier of the grid type and precision, and the scale, offset and invalid are
the arguments of optional modifiers to be applied to all grid values, Here, invalid is the
value used to indicate missing data. In case the id is not provided, as in +sscale, then
a id=nf is assumed. When reading grids, the format is generally automatically
recognized from almost all of those formats that GMT and GDAL combined offer. If not,
the same suffix can be added to input grid file names. See grdconvert and Section Grid
file format specifications of the GMT Technical Reference and Cookbook for more
information.

When reading a netCDF file that contains multiple grids, GMT will read, by default, the
first 2-dimensional grid that it can find in that file. To coax GMT into reading another
multi-dimensional variable in the grid file, append ?varname to the file name,
where varname is the name of the variable. Note that you may need to escape the
special meaning of ? in your shell program by putting a backslash in front of it, or by
placing the filename and suffix between quotes or double quotes. The ?varname suffix
can also be used for output grids to specify a variable name different from the default:
“z”. See grdconvert and Sections Modifiers for COARDS-compliant netCDF
files and Grid file format specifications of the GMT Technical Reference and Cookbook
for more information, particularly on how to read slices of 3-, 4-, or 5-dimensional grids.

When writing a netCDF file, the grid is stored by default with the variable name “z”. To
specify another variable name varname, append ?varname to the file name. Note that
you may need to escape the special meaning of ? in your shell program by putting a
backslash in front of it, or by placing the filename and suffix between quotes or double
quotes.

Classic Mode Options


These options are only used in classic mode and are listed here just for reference.

-K
More PostScript code will be appended later [Default terminates the plot system].
Required for all but the last plot command when building multi-layer plots.
-O

Selects Overlay plot mode [Default initializes a new plot system]. Required for all
but the first plot command when building multi-layer plots.
-P

Select “Portrait” plot orientation [Default is “Landscape”;


see gmt.conf or gmtset to change the PS_PAGE_ORIENTATION parameter, or
supply --PS_PAGE_ORIENTATION=orientation on the command line].

More information sources


Look up the individual man pages for more details and full syntax. Run gmt --help to list
all GMT programs and to show all installation directories. For an explanation of the
various GMT settings in this man page (like FORMAT_FLOAT_OUT), see the man
page of the GMT configuration file gmt.conf. Information is also available on the GMT
documentation site https://docs.generic-mapping-tools.org/

See Also
docs

gmt-config
Get information about the gmt installation

Synopsis
gmt-config [ options ]

Description
gmt-config is used by developers who need to know technical information about the
current GMT installation, such as what include files to supply, the path to the library, or if
it was built with GDAL support, and more.

Required Arguments
None.

Optional Arguments
--help

Display this help message and exit.


--all

Display all options.


--bits

Whether library is build 32-bit or 64-bit.


--cc

The C compiler used.


--cflags

The pre-processor and compiler flags used.


--datadir

GMT’s data directories.


--dataserver

The URL of the remote GMT data server.


--dcw
The location of the DCW database.
--dep-libs

The dependent libraries.


--gshhg

The location of the GSHHG database.


--has-fftw

Whether FFTW is used in build.


--has-gdal

Whether GDAL is used in build.


--has-pcre

Whether PCRE is used in build.


--has-lapack

Whether LAPACK is used in build.


--has-openmp

Whether GMT was built with OpenMP support.


--includedir

The include directory.


--libdir

The library directory.


--libs

The library linking information.


--plugindir

GMT’s plugin directory.


--prefix

The install prefix.


--version

The library version

Examples
To determine the compiler flags that is required for an external to to find the GMT
function prototypes, try:

gmt-config --cflags

See Also
gmt

gmt5syntax
Convert old GMT script to use new ‘gmt <module>’ syntax

Synopsis
gmt5syntax old_script > new_script

Description
gmt5syntax is a perl script that converts old-style GMT commands in, e.g., shell
scripts, to the new gmt <module> -syntax. This utility is located in the tools subdirectory of
the data directory. gmt --show-sharedir will show the path to the latter.

gmt_shell_functions.sh
gmt_shell_functions.sh - Practical functions to be used in GMT Bourne Again shell
scripts

Synopsis
gmt_init_tmpdir

gmt_remove_tmpdir

gmt_clean_up [ prefix ]

gmt_message message

gmt_abort message

gmt_build_movie [ -d directory ] [ -n ] [ -r framerate ] [ -v ] namestem

gmt_build_gif [ -d directory ] [ -l loop ] [ -r delay ] namestem

gmt_build_kmz -p prefix [ -r ] files


gmt_get_nrecords file(s)

gmt_get_ndatarecords file(s)

gmt_get_nfields string

gmt_get_field string

gmt_get_region file(s) [ options ]

gmt_get_gridregion file [ options ]

gmt_get_map_width -R -J

gmt_get_map_height -R -J

gmt_movie_script [ -c canvas OR -e dpi -h height -w width ] [ -f format ]

[ -g fill ] [ -n frames ] [ -m margin ] [ -r rate ] namestem

gmt_launch_jobs [ -c n_cores ] [ -l nlines_per_cluster ] [ -n ] [ -v ] [ -w ] commandfile

gmt_set_psfile scriptfile

gmt_set_pdffile scriptfile

gmt_set_framename prefix framenumber

gmt_set_framenext framenumber

Description
gmt_shell_functions.sh provides a set of functions to Bourne (again) shell scripts in
support of GMT. The calling shell script should include the following line, before the
functions can be used:

. gmt_shell_functions.sh
Once included in a shell script, gmt_shell_functions.sh allows GMT users to do some
scripting more easily than otherwise. The functions made available are:

gmt_init_tmpdir

Creates a temporary directory in /tmp or (when defined) in the directory specified


by the environment variable TMPDIR. The name of the temporary directory is
returned as environment variable GMT_TMPDIR. This function also causes GMT
to run in ‘isolation mode’, i.e., all temporary files will be created
in GMT_TMPDIR and the gmt.conf file will not be adjusted.
gmt_remove_tmpdir

Removes the temporary directory and unsets the GMT_TMPDIR environment


variable.
gmt_cleanup

Remove all files and directories in which the current process number is part of
the file name. If the optional prefix is given then we also delete all files and
directories that begins with the given prefix.
gmt_message

Send a message to standard error.


gmt_abort

Send a message to standard error and exit the shell.


gmt_get_nrecords

Returns the total number of lines in file(s)


gmt_get_ndatarecords

Returns the total number of data records in file(s), i.e., not counting headers.
gmt_get_nfields

Returns the number of fields or words in string


gmt_get_field
Returns the given field in a string. Must pass string between double quotes to
preserve it as one item.
gmt_get_region

Returns the region in the form w/e/s/n based on the data in table file(s).
Optionally add -Idx/dy to round off the answer.
gmt_get_gridregion

Returns the region in the form w/e/s/n based on the header of a grid file.
Optionally add -Idx/dy to round off the answer.
gmt_get_map_width

Expects the user to give the desired -R -J settings and returns the map width in
the current measurement unit.
gmt_get_map_height

Expects the user to give the desired -R -J settings and returns the map height in
the current measurement unit.
gmt_movie_script

Creates an animation bash script template based on the arguments that set size,
number of frames, video format etc. Without arguments the function will display
its usage.
gmt_launch_jobs

Takes a file with a long list of commands and splits them into many chunks that
can be executed concurrently. Without arguments the function will display its
usage. Note: It is your responsibility to make sure no race conditions occur (i.e.,
multiple commands writing to the same file).
gmt_set_psfile

Create the output PostScript file name based on the base name of a given file
(usually the script name $0).
gmt_set_framename

Returns a lexically ordered filename stem (i.e., no extension) given the file prefix
and the current frame number, using a width of 6 for the integer including leading
zeros. Useful when creating animations and lexically sorted filenames are
required.
gmt_set_framenext

Accepts the current frame integer counter and returns the next integer counter.
gmt_build_movie

Accepts a namestem which gives the prefix of a series of image files with
names dir/namestem_*.*. Optional argument sets the directory [same
as namestem ], and frame rate [24]. Without arguments the function will display
its usage.
gmt_build_gif

Accepts a namestem which gives the prefix of a series of image files with
names dir/namestem_*.*. Optional argument sets the directory [same
as namestem], loop count and frame rate [24]. Without arguments the function
will display its usage.
gmt_build_kmz

Accepts -p prefix [ -r ] and any number of KML files and and the images they
may refer to, and builds a single KMZ file with the name prefix.kmz. Without
arguments the function will display its usage.

Notes
1. These functions only work in the Bourne shell (sh) and their derivatives
(like ash, bash, ksh and zsh). These functions do not work in the C shell (csh) or their
derivatives (like tcsh), and cannot be used in DOS batch scripts either.

2. gmt_shell_functions.sh were first introduced in GMT version 4.2.2 and have since
been regularly expanded with other practical scripting short-cuts. If you want to suggest
other functions, please do so by adding a New Issue request
on https://github.com/GenericMappingTools/gmt.
gmtswitch
Switching between different GMT versions

Synopsis
gmtswitch [ D | version ]

Introduction
gmtswitch helps you modify your environment to allow for the switching back and forth
between several installed GMT versions. It works by maintaining a list of directories to
GMT installations in a file in your home directory, then manipulates a symbolic link to
point to the GMT directory whose executables we wish to use [The Windows version
works a bit differently; see WINDOWS below].

Required Arguments
None. If no arguments are given you are presented with a menu of installed GMT
versions from 1 to n and you specify which one you wish to switch to.

Optional Arguments
D

Select the default GMT version. This is the first entry in the ~/.gmtversions file
version

Search for a unique match in the ~/.gmtversions file. If one match is found we
switch to that entry; otherwise an error is generated. where module is the name
of a GMT program and the options are those that pertain to that particular
program.

Setup
If you have official versions installed then running gmtswitch the very first time will
examine your hard disk starting at / and look for directories with GMT4, GMT5, etc., in
the names. This will fail to find the subversion directories and possibly others you have
placed elsewhere. The fastest way to get up and running is this:

1. Edit/Create ~/.gmtversions and add the paths to all GMT installations

you have or care to consider. Each path goes on separate lines and points to the
top dir of each distribution, e.g.,
/Users/pwessel/UH/RESEARCH/PROJECTS/GMTdev/gmt-4.5.18
2. In your .bashrc or .[t]csrh or wherever you are maintaining your PATH

or path variable, remove any directories you have added that contain GMT, and
add the new path $HOME/this_gmt/bin (might be $home for csh users). Make
sure this path appears before any others that might contain a GMT installation,
such as those used by package managers (e.g., /sw/bin for fink, /opt/local/bin for
Macports, etc.).
3. Make the new path take effect (quit/restart terminal, logout/login, etc).
4. cd to the most recent GMT directory where a gmtswitch version lives,

and run gmtswitch with no argument. Select one of the version from the menu.
5. If in csh you may have to say rehash afterwards.
6. Type “plot -” and the synopsis should tell you that you got the

correct version. You can now run gmtswitch from anywhere; try it out and make
sure that you can switch between the versions.
Examples
To switch to GMT version 4.5.18 (assuming it was installed as such and not via a
package manager), try

gmtswitch gmt-4.5.18

To switch to the default (your top choice), do

gmtswitch D

Finally, to select from the menu, just run


gmtswitch

and pick the one you want.

Beware
GMT remembers where it was installed the first time and uses that dir to find the default
GMT share directory. If you move entire GMT installation after compilation then you
may have to set GMT_SHAREDIR to point to the top dir in order for things to work. It is
best not to move things after installation.

Windows
Under Windows use gmtswitch.bat which is a batch script that changes the Windows
PATH variable so that the BIN directory of the preferred version always comes first. To
do that the batch works in two alternative modes:

1 - Permanent mode

2 - Temporary mode

The permanent mode makes use of the free executable program “EditPath” to change
the user path in the registry. It’s called permanent because the changes remains until …
next change. See

http://www.softpedia.com/get/Tweak/Registry-Tweak/EditPath.shtml

Of course the editpath.exe binary must be in your system’s path as well. WARNING:
The path change will not be visible on the shell cmd where it was executed. For the
change to be active you will need to open a new cmd window.

The second mode is temporary because the path to the selected GMT binary dir is
prepended to the previous path via a shell command line. This modification disappears
when the shell cmd window where it was executes is deleted.
It is the user responsibility to set the contents of the G32_32 to G5_64 below to valid
paths where the binaries of the different GMT versions are installed Note that it is not
mandatory to have all four of them in you computer. For the ones you do not have just
let them pointing to nothing e.g.,

set G4_64=

The permanent mode is the default one (but this can be changed. See edit section) To
run in the temporary mode just give a second argument (doesn’t matter what)

Example usage to set a GMT5 64 bits permanent

gmtswitch g5_64

To temporary set a GMT4 32 bits do

gmtswitch g4_32 1

Run without arguments to get a “Usage” (for permanent mode)

img2google
img2google - Create Google Earth KML overlay tiles from bathymetry Mercator img grid

Synopsis
img2google -Rregion [ imgfile ] [ -Amode[altitude] ] [ -C ] [ -Ffademin/fademax ] [ -
Gprefix ] [ -LLODmin/LODmax ] [ -Nlayername ] [ -Tdoctitle ] [ -UURL ] [ -V[level] ] [ -Z ]
[ --PAR=value ]

Description
img2google is a shell script that reads a 1x1 minute Mercator surface relief img file and
creates a Google Earth overlay KML file and associated PNG tile for the specified
region. If no input file is given we use topo.18.1.img.

-Rwest/east/south/north[/zmin/zmax][+r][+uunit]

west, east, south, and north specify the region of interest, and you may specify
them in decimal degrees or in [±]dd:mm[:ss.xxx][W|E|S|N] format Append +r if
lower left and upper right map coordinates are given instead of w/e/s/n. The two
shorthands -Rg and -Rd stand for global domain (0/360 and -180/+180 in
longitude respectively, with -90/+90 in latitude). Set geographic regions by
specifying ISO country codes from the Digital Chart of the World using -
Rcode1,code2,…[+r|R[incs]] instead: Append one or more comma-separated
countries using the 2-character ISO 3166-1 alpha-2 convention. To select a state
of a country (if available), append .state, e.g, US.TX for Texas. To specify a
whole continent, prepend = to any of the continent codes AF (Africa), AN
(Antarctica), AS (Asia), EU (Europe), OC (Oceania), NA (North America), or SA
(South America). Use +r to modify the bounding box coordinates from the
polygon(s): Append inc, xinc/yinc, or winc/einc/sinc/ninc to adjust the region to be
a multiple of these steps [no adjustment]. Alternatively, use +R to extend the
region outward by adding these increments instead, or +e which is like +r but it
ensures that the bounding box extends by at least 0.25 times the increment [no
extension]. Alternatively for grid creation, give Rcodelon/lat/nx/ny, where code is
a 2-character combination of L, C, R (for left, center, or right) and T, M, B for top,
middle, or bottom. e.g., BL for lower left. This indicates which point on a
rectangular region the lon/lat coordinate refers to, and the grid
dimensions nx and ny with grid spacings via -I is used to create the
corresponding region. Alternatively, specify the name of an existing grid file and
the -R settings (and grid spacing and registration, if applicable) are copied from
the grid. Appending +uunit expects projected (Cartesian) coordinates compatible
with chosen -J and we inversely project to determine actual rectangular
geographic region. For perspective view (-p), optionally append /zmin/zmax. In
case of perspective view (-p), a z-range (zmin, zmax) can be appended to
indicate the third dimension. This needs to be done only when using the -
Jz option, not when using only the -p option. In the latter case a perspective view
of the plane is plotted, with no third dimension.
Options
imgfile

An img format bathymetry/topography file such as those created by Sandwell and


Smith. If this files does not exist in the current directory and the user has set the
environment variable $GMT_DATADIR, then img2grd will try to
find imgfile in $GMT_DATADIR.
-A

Selects one of 5 altitude modes recognized by Google Earth that determines the
altitude (in m) of the image: G clamped to the ground, g append altitude relative
to ground, a append absolute altitude, s append altitude relative to seafloor,
and S clamp it to the seafloor [Default].
-C

Turn on clipping so that only portions below sea level will be visible in the image
[no clipping].
-F

Sets the distance over which the geometry fades, from fully opaque to fully
transparent. These ramp values, expressed in screen pixels, are applied at the
minimum and maximum end of the LOD (visibility) limits, respectively. [no fading
(0/0)].
-G

Specify the prefix for the output image file (the extensions are set automatically).
Default uses the naming topoN|S<north>E|W<west>.
-L

Measurement in screen pixels that represents the minimum limit of the visibility
range for a given Region Google Earth calculates the size of the Region when
projected onto screen space. Then it computes the square root of the Region’s
area (if, for example, the Region is square and the viewpoint is directly above the
Region, and the Region is not tilted, this measurement is equal to the width of the
projected Region). If this measurement falls within the limits defined
by LODmin and LODmax (and if the region is in view), the Region is active. If this
limit is not reached, the associated geometry is considered to be too far from the
user’s viewpoint to be drawn. LODmax represents the maximum limit of the
visibility range for a given Region. A value of 1, the default, indicates “active to
infinite size.” [always active].
-N

Append the layername of the image (use quotes if strings contain spaces)
[topoN|S<north>E|W<west>].
-T

Append the document title (use quotes if strings contain spaces) [“Predicted
bathymetry”].
-U

By default, images are referenced locally relative to the KML file. Specify an URL
to prepend a server address to the image name reference [local].
-V[level]

Select verbosity level [w]. (See full description) (See cookbook information).
-Z

Uses zip (which must be installed) to create a *.kmz file for easy distribution;
append + to delete the KML and PNG file after zipping [No zipping].

Examples
To create a 10x10 degree Google Earth KML tile for the region -R170/180/20/30 using
the default topo.18.1.img and output naming convention, try

img2google -R170/180/20/30

To make the same tile with a previous file such as topo.15.1.img, run in verbose mode,
clip so only oceanic areas are visible, name the output oldimage, specify the KML
metadata directly (including setting the image altitude to 10 km), and make a single
*.kmz file, try

img2google topo.15.1.img -R170/180/20/30 -Aa10000 -C -Goldimage \


-N"My KML title" -T"My KML title" -Uhttp://my.server.com/images -V -Z

DATA SETS
For topo.18.1.img and other Sandwell/Smith altimetry-derived Mercator grids,
visit http://topex.ucsd.edu.

basemap
Plot base maps and frames

Synopsis
gmt basemap -Jparameters -Rwest/east/south/north[/zmin/zmax][+r][+uunit] [ -A[file] ]
[ -B[p|s]parameters ] [ -Fbox ] [ -Jz|Zparameters ] [ -Lscalebar ] [ -Trose ] [ -
Tmag_rose ] [ -U[stamp] ] [ -V[level] ] [ -X[a|c|f|r][xshift] ] [ -Y[a|c|f|r][yshift] ] [ -fflags ] [ -
pflags ] [ -ttransp ] [ --PAR=value ]

Note: No space is allowed between the option flag and the associated arguments.

Description
Creates a basic or fancy basemap with axes, fill, and titles. Several map projections are
available, and the user may specify separate tick-mark intervals for boundary
annotation, ticking, and (optionally) gridlines. A simple map scale (-L) or directional rose
(-T) may also be plotted. At least one of the options -B, -L, or -T must be specified.

Required Arguments
-Jparameters

Specify the projection. (See full description) (See cookbook summary) (See
projections table).
-Rxmin/xmax/ymin/ymax[+r][+uunit]
Specify the region of interest. (See full description) (See cookbook information).

For perspective view -p, optionally append /zmin/zmax. (more …)

Optional Arguments
-A[file]

No plotting is performed. Instead, we determine the geographical coordinates of


the polygon outline for the (possibly oblique) rectangular map domain. The plot
domain must be given via -R and -J, with no other options allowed. The sampling
interval is controlled via MAP_LINE_STEP parameter. The coordinates are
written to file or to standard output if no file is specified.
-B[p|s]parameters

Set map boundary frame and axes attributes. (See full description) (See
cookbook information).

-F[d|l|t][+cclearances][+gfill][+i[[gap/]pen]][+p[pen]][+r[radius]][+s[[dx/dy/][shade]]]

Without further options, draws a rectangular border around any map inset (-D; classic
mode only), map scale (-L) or map rose (-T) using MAP_FRAME_PEN. Used in
combination with -D, -L or -T. Append d for map inset, l for map scale, or t for map rose
to specify which plot embellisment the -F parameters should be applied to [default uses
the same panel parameters for all selected map embellishments]. The following
modifiers can be appended to -F, with additional explanation and examples provided in
the The background panel cookbook section:

 +cclearance where clearance is either gap, xgap/ygap,


or lgap/rgap/bgap/tgap and gap gives a uniform clearance, xgap/ygap gives
separate clearances in the x- and y- directions, and lgap/rgap/bgap/tgap gives
individual clearances between the map embellishment and the border for each
side.
 +gfill to fill the box with a color specified by fill [default is no fill].
 +i[[gap/]pen] to draw a secondary, inner border as well. Optionally, specify
the gap between the inner and outer border and the pen for the inner border
[default is a uniform gap between borders of 2p and the MAP_DEFAULT_PEN].
 +ppen to specify different pen attributes.
 +r[radius] to draw rounded rectangular borders instead with a corner radius set
by radius (append units) [defaults is 6p].
 +s[[dx/dy/][shade]] to draw an offset background shaded region.
Here, dx/dy indicates the shift relative to the foreground frame [default is 4p/-4p]
and shade sets the fill style to use for shading [default is gray50].

-L[g|j|J|n|x]refpoint+wlength[e|f|k|M|n|u][+aalign][+c[[slon/]slat]][+f][+jjustify][+l[label]]
[+odx[/dy]][+u][+v]

Draw a simple map scale at the location defined by the reference (refpoint) and anchor
point (set by +odx[/dy] and/or +jjustify). Give the reference point on the map for the rose
using one of four coordinate systems:

1. Append glon/lat for map coordinates. Requires both -R and -J to be set.


2. Append jcode or Jcode for setting the refpoint via a 2-char justification code that
refers to the (invisible) projected map bounding box. Requires both -R and -J to
be set.
3. Append nxn/yn for normalized bounding box coordinates (0-1). Requires both -
R and -J to be set.
4. Append xx/y for plot coordinates (append cm, inch, or ppoint).
The following modifiers can be appended to -L (+w is required), with additional
explanation and examples provided in the Placing map scales cookbook section. For
Cartesian projectsion, the modifiers +c and +f are not allowed and no units should be
appended in +w.

 +wlength to set scale length in km, or append unit from e|f|k|M|n|u.


 +aalign to change the label alignment (choose among l(eft), r(ight), t(op),
and b(ottom)) [default is t(op)].
 +c[[slon/]slat]] to control where on a geographic map the scale applies. Map
scale is calculated for latitude slat (optionally supply longitude slon for oblique
projections [default is central meridian]). If +c is not given we default to the
location of the refpoint. If +c is given with no arguments then we select the scale
origin to be the middle of the map.
 +f to get a “fancy” scale [default is plain].
 +jjustify to set the justification anchor point, where justify is a 2-
character justification code that is a combination of a horizontal (L, C, or R) and a
vertical (T, M, or B) code. Note: If j is used to set the reference point
then justify defaults to the same as refpoint; if J is used then justify defaults to the
mirror opposite of refpoint; if g, n, or x is used to set the reference point
then justify defaults to MC.
 +l[label] to add a scale label. If label is not provided, we use the distance unit
provided in +w [default is k(m)]. The label alignment is set by +a [default is t(op)].
Requires +f.
 +odx[/dy] to offset the anchor point by dx and optionally dy (if different than dx).
 +u to append the unit set by +w to all distance annotations along the scale (for
the plain scale, +u will instead select the unit to be appended to the distance
length).
 +v to get a vertical rather than a horizontal Cartesian scale.
Note: Use FONT_LABEL to change the label font and FONT_ANNOT_PRIMARY to
change the annotation font. The height of the map scale is controlled
by MAP_SCALE_HEIGHT, and the pen thickness is set
by MAP_TICK_PEN_PRIMARY. Optionally, use -F to place a panel behind the scale.

-Td[g|j|J|n|x]refpoint+wwidth[+f[level]][+jjustify][+l[w,e,s,n]][+odx[/dy]]

Draw a map directional rose on the map at the location defined by the reference
(refpoint) and anchor point (set by +odx[/dy] and/or +jjustify). Give the reference point
on the map for the rose using one of four coordinate systems:

1. Append glon/lat for map coordinates. Requires both -R and -J to be set.


2. Append jcode or Jcode for setting the refpoint via a 2-char justification code that
refers to the (invisible) projected map bounding box. Requires both -R and -J to
be set.
3. Append nxn/yn for normalized bounding box coordinates (0-1). Requires both -
R and -J to be set.
4. Append xx/y for plot coordinates (append cm, inch, or ppoint).
The following modifiers can be appended to -Td (+w is required), with additional
explanation and examples provided in the Placing directional map roses cookbook
section. Optionally, use -F to place a panel behind the directional rose.

 +wwidth to set the width of the rose in plot coordinates (append inch, cm,
or points).
 +f[level] to get a “fancy” rose, and optionally specify the level of fanciness.
Level 1 draws the two principal E-W, N-S orientations, 2 adds the two
intermediate NW-SE and NE-SW orientations, while 3 adds the eight minor
orientations WNW-ESE, NNW-SSE, NNE-SSW, and ENE-WSW [default is 1].
 +jjustify to set the justification anchor point, where justify is a 2-
character justification code that is a combination of a horizontal (L, C, or R) and a
vertical (T, M, or B) code. Note: If j is used to set the reference point
then justify defaults to the same as refpoint; if J is used then justify defaults to the
mirror opposite of refpoint; if g, n, or x is used to set the reference point
then justify defaults to MC.
 +l[w,e,s,n] to label the cardinal points W,E,S,N. Optionally, append your own four
comma-separated strings to override the default. Skip a specific label by leaving
it blank.
 +odx[/dy] to offset the anchor point by dx and optionally dy (if different than dx).

-Tm[g|j|J|n|x]refpoint+wwidth[+ddec[/dlabel]]][+ipen][+jjustify][+l[w,e,s,n]][+ppen][+tints]
[+odx[/dy]]

Draw a map magnetic rose on the map at the location defined by the reference
(refpoint) and anchor point (set by +odx[/dy] and/or +jjustify). Give the reference point
on the map for the rose using one of four coordinate systems:

1. Append glon/lat for map coordinates. Requires both -R and -J to be set.


2. Append jcode or Jcode for setting the refpoint via a 2-char justification code that
refers to the (invisible) projected map bounding box. Requires both -R and -J to
be set.
3. Append nxn/yn for normalized bounding box coordinates (0-1). Requires both -
R and -J to be set.
4. Append xx/y for plot coordinates (append cm, inch, or ppoint).
The following modifiers can be appended to -Tm (+w is required), with additional
explanation and examples provided in the Placing magnetic map roses cookbook
section. Optionally, use -F to place a panel behind the magnetic rose.

 +wwidth to set the width of the rose in plot coordinates (append inch, cm,
or points).
 +ddec[/dlabel] to assign the magnetic declination and set dlabel, which is a label
for the magnetic compass needle (omit dlabel to format a label from dec, or
give - to bypass labeling). With +d, both directions to geographic and magnetic
north are plotted [default is geographic only].
 +ipen to draw the outline of the inner circle in the specified pen.
 +jjustify to set the justification anchor point, where justify is a 2-
character justification code that is a combination of a horizontal (L, C, or R) and a
vertical (T, M, or B) code. Note: If j is used to set the reference point
then justify defaults to the same as refpoint; if J is used then justify defaults to the
mirror opposite of refpoint; if g, n, or x is used to set the reference point
then justify defaults to MC.
 +l[w,e,s,n] to label the cardinal points W,E,S,N and append your own four
comma-separated strings to override the default. Skip a specific label by leaving
it blank. If the north label is * then a north star is plotted instead of the north label.
 +ppen to draw the outline of the outer circle in the specified pen.
 +tints to specify the annotation and two tick interval levels for the geographic and
magnetic directions by providing three slash-separated intervals. Specify
separate intervals by appending three slash-separated geographic intervals
followed by three slash-separated magnetic intervals [default is 30/5/1]
 +odx[/dy] to offset the anchor point by dx and optionally dy (if different than dx).
-U[label|+c][+jjust][+odx/dy]

Draw GMT time stamp logo on plot. (See full description) (See cookbook
information).
-V[level]

Select verbosity level [w]. (See full description) (See cookbook information).
-X[a|c|f|r][xshift]

Shift plot origin. (See full description) (See cookbook information).


-Y[a|c|f|r][yshift]

Shift plot origin. (See full description) (See cookbook information).


-f[i|o]colinfo (more …)

Specify data types of input and/or output columns. This applies only to the
coordinates specified in the -R option.
-p[x|y|z]azim[/elev[/zlevel]][+wlon0/lat0[/z0]][+vx0/y0] (more …)

Select perspective view.


-ttransp[/transp2] (more …)

Set transparency level(s) in percent.


-^ or just -

Print a short message about the syntax of the command, then exit (NOTE: on
Windows just use -).
-+ or just +

Print an extensive usage (help) message, including the explanation of any


module-specific option (but not the GMT common options), then exit.
-? or no arguments

Print a complete usage (help) message, including the explanation of all options,
then exit.
--PAR=value

Temporarily override a GMT default setting; repeatable. See gmt.conf for


parameters.

Examples
Note: Since many GMT plot examples are very short (i.e., one module call between
the gmt begin and gmt end commands), we will often present them using the quick
modern mode GMT Modern Mode One-line Commands syntax, which simplifies such
short scripts.

The following section illustrates the use of the options by giving some examples for the
available map projections. Note how scales may be given in several different ways
depending on the projection. Also note the use of upper case letters to specify map
width instead of map scale.

Non-geographical Projections
Linear x-y plot
To make a linear x/y frame with all axes, but with only left and bottom axes annotated,
using xscale = yscale = 1cm per unit, ticking every 1 unit and annotating every 2, and
using xlabel = “Distance” and ylabel = “No of samples”, use

gmt begin linear


gmt basemap -R0/9/0/5 -Jx1c -Bf1a2 -Bx+lDistance -By+l"No of samples" -BWeSn
gmt end show

As mentioned above, such simple modern mode script can take advantage of the one-
liner format. We repeat the same example using the one-liner format and then only
show this format for the remaining examples:

gmt basemap -R0/9/0/5 -Jx1c -Bf1a2 -Bx+lDistance -By+l"No of samples" -BWeSn -pdf
linear

Log-log plot

To make a log-log frame with only the left and bottom axes, where the x-axis is 25 cm
and annotated every 1-2-5 and the y-axis is 15 cm and annotated every power of 10 but
has tick-marks every 0.1, run

gmt basemap -R1/10000/1e20/1e25 -JX25cl/15cl -Bx2+lWavelength -Bya1pf3+lPower -BWS -


pdf loglog

Power axes

To design an axis system to be used for a depth-sqrt(age) plot with depth positive down,
ticked and annotated every 500m, and ages (in millions of years) annotated at 1 My, 4
My, 9 My etc., use

gmt basemap -R0/100/0/5000 -Jx1cp0.5/-0.001c -Bx1p+l"Crustal age" -By500+lDepth -pdf


power

Polar (theta,r) plot

For a base map for use with polar coordinates, where the radius from 0 to 1000 should
correspond to 3 inch and with gridlines and ticks intervals automatically determined, use
gmt basemap -R0/360/0/1000 -JP6i -Bafg -pdf polar

Cylindrical Map Projections


Cassini

A 10-cm-wide basemap using the Cassini projection may be obtained by

gmt basemap -R20/50/20/35 -JC35/28/10c -Bafg -B+tCassini -pdf cassini

Mercator [conformal]

A Mercator map with scale 0.025 inch/degree along equator, and showing the length of
5000 km along the equator (centered on 1/1 inch), may be plotted as

gmt basemap -R90/180/-50/50 -Jm0.025i -Bafg -B+tMercator -Lx1i/1i+c0+w5000k -pdf


mercator

Miller

A global Miller cylindrical map with scale 1:200,000,000 may be plotted as

gmt basemap -Rg -Jj180/1:200000000 -Bafg -B+tMiller -pdf miller

Oblique Mercator [conformal]

To create a page-size global oblique Mercator basemap for a pole at (90,30) with
gridlines every 30 degrees, run

gmt basemap -R0/360/-70/70 -Joc0/0/90/30/0.064cd -B30g30 -B+t"Oblique Mercator" -pdf


oblmerc

Transverse Mercator [conformal]

A regular Transverse Mercator basemap for some region may look like
gmt basemap -R69:30/71:45/-17/-15:15 -Jt70/1:1000000 -Bafg -B+t"Survey area" -pdf
transmerc

Equidistant Cylindrical Projection

This projection only needs the central meridian and scale. A 25 cm wide global
basemap centered on the 130E meridian is made by

gmt basemap -R-50/310/-90/90 -JQ130/25c -Bafg -B+t"Equidistant Cylindrical" -pdf


cyl_eqdist

Universal Transverse Mercator [conformal]

To use this projection you must know the UTM zone number, which defines the central
meridian. A UTM basemap for Indo-China can be plotted as

gmt basemap -R95/5/108/20r -Ju46/1:10000000 -Bafg -B+tUTM -pdf utm

Cylindrical Equal-Area

First select which of the cylindrical equal-area projections you want by deciding on the
standard parallel. Here we will use 45 degrees which gives the Gall projection. A 9 inch
wide global basemap centered on the Pacific is made by

gmt basemap -Rg -JY180/45/9i -Bafg -B+tGall -pdf gall

Conic Map Projections


Albers [equal-area]

A basemap for middle Europe may be created by

gmt basemap -R0/90/25/55 -Jb45/20/32/45/0.25c -Bafg -B+t"Albers Equal-area" -pdf


albers

Lambert [conformal]
Another basemap for middle Europe may be created by

gmt basemap -R0/90/25/55 -Jl45/20/32/45/0.1i -Bafg -B+t"Lambert Conformal Conic" -pdf


lambertc

Conic Equidistant

Yet another basemap of width 6 inch for middle Europe may be created by

gmt basemap -R0/90/25/55 -JD45/20/32/45/6i -Bafg -B+t"Equidistant conic" -pdf econic

Polyconic

A basemap for north America may be created by

gmt basemap -R-180/-20/0/90 -JPoly/4i -Bafg -B+tPolyconic -pdf polyconic

Azimuthal Map Projections


Lambert [equal-area]

A 15-cm-wide global view of the world from the vantage point -80/-30 will give the
following basemap:

gmt basemap -Rg -JA-80/-30/15c -Bafg -B+t"Lambert Azimuthal" -pdf lamberta

Follow the instructions for stereographic projection if you want to impose rectangular
boundaries on the azimuthal equal-area map but substitute -Ja for -Js.

Azimuthal Equidistant

A 15-cm-wide global map in which distances from the center (here 125/10) to any point
is true can be obtained by:

gmt basemap -Rg -JE125/10/15c -Bafg -B+tEquidistant -pdf equi


Gnomonic

A view of the world from the vantage point -100/40 out to a horizon of 60 degrees from
the center can be made using the Gnomonic projection:

gmt basemap -Rg -JF-100/40/60/6i -Bafg -B+tGnomonic -pdf gnomonic

Orthographic

A global perspective (from infinite distance) view of the world from the vantage point
125/10 will give the following 6-inch-wide basemap:

gmt basemap -Rg -JG125/10/6i -Bafg -B+tOrthographic -pdf ortho

General Perspective

The -JG option can be used in a more generalized form, specifying altitude above the
surface, width and height of the view point, and twist and tilt. A view from 160 km above
-74/41.5 with a tilt of 55 and azimuth of 210 degrees, and limiting the viewpoint to 30
degrees width and height will product a 6-inch-wide basemap:

gmt basemap -Rg -JG-74/41.5/160/210/55/30/30/6i -Bafg -B+t"General Perspective" -pdf


genper

Stereographic [conformal]

To make a polar stereographic projection basemap with radius = 12 cm to -60 degree


latitude, with plot title “Salinity measurements”, using 5 degrees annotation/tick interval
and 1 degree gridlines, run

gmt basemap -R-45/45/-90/-60 -Js0/-90/12c/-60 -B5g1 -B+t"Salinity measurements" -pdf


stereo1
To make a 12-cm-wide stereographic basemap for Australia from an arbitrary view point
(not the poles), and use a rectangular boundary, we must give the pole for the new
projection and use the -R option to indicate the lower left and upper right corners (in
lon/lat) that will define our rectangle. We choose a pole at 130/-30 and use 100/-45 and
160/-5 as our corners. The command becomes

gmt basemap -R100/-45/160/-5r -JS130/-30/12c -Bafg -B+t"General Stereographic View" -


pdf stereo2

Miscellaneous Map Projections


Hammer [equal-area]

The Hammer projection is mostly used for global maps and thus the spherical form is
used. To get a world map centered on Greenwich at a scale of 1:200000000, use

gmt basemap -Rd -Jh0/1:200000000 -Bafg -B+tHammer -pdf hammer

Sinusoidal [equal-area]

To make a sinusoidal world map centered on Greenwich, with a scale along the equator
of 0.02 inch/degree, use

gmt basemap -Rd -Ji0/0.02i -Bafg -B+tSinusoidal -pdf sinus1

To make an interrupted sinusoidal world map with breaks at 160W, 20W, and 60E, with
a scale along the equator of 0.02 inch/degree, run the following sequence of
commands:

gmt begin
gmt basemap -R-160/-20/-90/90 -Ji-90/0.02i -Bx30g30 -By15g15 -BWesn
gmt basemap -Bx30g30 -By15g15 -Bwesn -X2.8i
gmt basemap -Bx30g30 -By15g15 -BwEsn -X1.6i
gmt end show

Eckert IV [equal-area]
Pseudo-cylindrical projection typically used for global maps only. Set the central
longitude and scale, e.g.,

gmt basemap -Rg -Jkf180/0.064c -Bafg -B+t"Eckert IV" -pdf eckert4

Eckert VI [equal-area]

Another pseudo-cylindrical projection typically used for global maps only. Set the central
longitude and scale, e.g.,

gmt basemap -Rg -Jks180/0.064c -Bafg -B+t"Eckert VI" -pdf eckert6

Robinson

Projection designed to make global maps “look right”. Set the central longitude and
width, e.g.,

gmt basemap -Rd -JN0/8i -Bafg -B+tRobinson -pdf robinson

Winkel Tripel

Yet another projection typically used for global maps only. You can set the central
longitude, e.g.,

gmt basemap -R90/450/-90/90 -JR270/25c -Bafg -B+t"Winkel Tripel" -pdf winkel

Mollweide [equal-area]

The Mollweide projection is also mostly used for global maps and thus the spherical
form is used. To get a 25-cm-wide world map centered on the Dateline:

gmt basemap -Rg -JW180/25c -Bafg -B+tMollweide -pdf mollweide

Van der Grinten


The Van der Grinten projection is also mostly used for global maps and thus the
spherical form is used. To get a 18-cm-wide world map centered on the Dateline:

gmt basemap -Rg -JV180/18c -Bafg -B+t"Van der Grinten" -pdf grinten

Arbitrary rotation

If you need to plot a map but have it rotated about a vertical axis then use the -P option.
For instance, to rotate the basemap below 90 degrees about an axis centered on the
map, try

gmt basemap -R10/40/10/40 -JM10c -Bafg -B+t"I am rotated" -p90+w25/25 -Xc -pdf rotated

Custom Labels or Intervals


The -B option sets up a regular annotation interval and the annotations derive from the
corresponding x, y, or z coordinates. However, some applications requires special
control on which annotations to plot and even replace the annotation with other labels.
This is achieved by using cintfile in the -B option, where intfile contains all the
information about annotations, ticks, and even gridlines. Each record is of the
form coord type [label], where coord is the coordinate for this annotation (or tick or
gridline), type is one or more letters from a (annotation), i interval annotation, f tickmark,
and g gridline. Note that a and i are mutually exclusive and cannot both appear in the
same intfile. Both a and i requires you to supply a label which is used as the plot
annotation. If not given then a regular formatted annotation based on the coordinate will
occur.

Restrictions
For some projections, a spherical earth is implicitly assumed. A warning will notify the
user if -V is set.

Bugs
The -B option is somewhat complicated to explain and comprehend. However, it is fairly
simple for most applications (see examples).

batch
Automate batch job processing

Synopsis
gmt batch mainscript -Nprefix -Tnjobs|min/max/inc[+n]|timefile[+pwidth][+sfirst][+w[str]]
[ -Iincludefile ] [ -M[job] ] [ -Q[s] ] [ -Sbpreflight ] [ -Sfpostflight ] [ -V[level] ] [ -W[workdir] ]
[ -Z ] [ -x[[-]n] ] [ --PAR=value ]

Note: No space is allowed between the option flag and the associated arguments.

Description
The batch module can generate GMT processing jobs using a single master script that
is repeated for all jobs, with some variation using specific job variables. The module
simplifies (and hides) most of the steps normally needed to set up a full-blown
processing sequence. Instead, the user can focus on composing the main processing
script and let the parallel execution of jobs be automatic. We can set up required data
sets and do one-time calculations via an optional preflight script. After completion we
can optionally assemble the data output and make summary plots or similar in
the postflight script.

Required Arguments
mainscript

Name of a stand-alone GMT modern mode processing script that makes the
parameter-dependent calculations. The script may access job variables, such as
job number and others defined below, and may be written using the Bourne shell
(.sh), the Bourne again shell (.bash), the csh (.csh) or DOS batch language
(.bat). The script language is inferred from the file extension and we build hidden
batch scripts using the same language. Parameters that can be accessed are
discussed below.
-Nprefix

Determines the prefix of the batch file products and the final sub-directory with all
job products.
-Tnjobs|min/max/inc[+n]|timefile[+pwidth][+sfirst][+w[str]]

Either specify how many jobs to make, create a one-column data set width
values from min to max every inc (append +n if inc is number of jobs instead), or
supply a file with a set of parameters, one record (i.e., row) per job. The values in
the columns will be available to the mainscript as named
variables BATCH_COL0, BATCH_COL1, etc., while any trailing text can be
accessed via the variable BATCH_TEXT. Append +w to split the trailing string
into individual words that can be accessed via
variables BATCH_WORD0, BATCH_WORD1, etc. By default we use any white-
space to separate words. Append str to select another character(s) as the valid
separator(s). The number of records equals the number of jobs. Note that
the preflight script is allowed to create timefile, hence we check for its existence
both before and after the preflight script has completed. Normally, the job
numbering starts at 0; you can change this by appending a different starting job
number via +sfirst. Note: All jobs are still included; this modifier only affects the
numbering of the given jobs. Finally, +p can be used to set the tag width of the
format used in naming jobs. For instance, name_000010.grd has a tag width of 6.
By default, this is automatically set but if you are splitting large jobs across
several computers (via +s) then you must use the same tag width for all names.

Optional Arguments
-Iincludefile

Insert the contents of includefile into the batch_init.sh script that is accessed by
all batch scripts. This mechanism is used to add information (typically constant
variable assignments) that the mainscript and any optional -S scripts can rely on.
-M[job]
Instead of making and launching the full processing sequence, select a single
master job [0] for testing. The master job will be run and its product(s) are placed
in the top directory. While any preflight script will be run prior to the master job,
the postflight script will not be executed (but it will be created).
-Q[s]

Debugging: Leave all files and directories we create behind for inspection.
Alternatively, append s to only build the batch scripts but not perform any
executions. One exception involves the optional preflight script derived from -
Sb which is always executed since it may produce data needed when building
the main batch (or master) scripts.
-Sbpreflight

The optional GMT modern mode preflight (written in the same scripting language
as mainscript) can be used to download or copy data files or create files (such
as timefile) that will be needed by mainscript. It is always run before the main
sequence of batch scripts.
-Sfpostflight

The optional postflight (written in the same scripting language as mainscript) can
be used to perform final processing steps following the completion of all the
individual jobs, such as assembling all the products into a single larger file. The
script may also make one or more illustrations using the products or stacked data
after the main processing is completed. It does not have to be a GMT script.
-V[level]

Select verbosity level [w]. (See full description) (See cookbook information).
-W[workdir]

By default, all temporary files and job products are created in the
subdirectory prefix set via -N. You can override that selection by giving
another workdir as a relative or full directory path. If no path is given then we
create a working directory in the system temp folder named prefix. The main
benefit of a working directory is to avoid endless syncing by agents like DropBox
or TimeMachine, or to avoid problems related to low space in the main directory.
The product files will still be placed in the prefix directory. The workdir is removed
unless -Q is specified for debugging.
-Z

Erase the mainscript and all input scripts given via -I and -S upon completion.
Not compatible with -Q.
-x[[-]n]

Limit the number of cores to use when loading up the cores. By default we try to
use all available cores. Append n to only use n cores (if too large it will be
truncated to the maximum cores available). Finally, give a negative n to select
(all - n) cores (or at least 1 if n equals or exceeds all). The parallel processing
does not depend on OpenMP; new jobs are launched when the previous ones
complete.
-^ or just -

Print a short message about the syntax of the command, then exit (NOTE: on
Windows just use -).
-+ or just +

Print an extensive usage (help) message, including the explanation of any


module-specific option (but not the GMT common options), then exit.
-? or no arguments

Print a complete usage (help) message, including the explanation of all options,
then exit.
--PAR=value

Temporarily override a GMT default setting; repeatable. See gmt.conf for


parameters.

Parameters
Several parameters are automatically assigned and can be used when composing
the mainscript and the optional preflight and postflight scripts. There are two sets of
parameters: Those that are constants and those that change with the job number. The
constants are accessible by all the scripts: BATCH_PREFIX: The common prefix of the
batch jobs (it is set with -N). BATCH_NJOBS: The total number of jobs (given or
inferred from -T). Also, if -I was used then any static parameters listed therein will be
available to all the scripts as well. In addition, the mainscript also has access to
parameters that vary with the job counter: BATCH_JOB: The current job number (an
integer, e.g., 136), BATCH_TAG: The formatted job number given the precision (a
string, e.g., 000136), and BATCH_NAME: The name prefix unique to the current job
(i.e., prefix_BATCH_TAG), Furthermore, if a timefile was given then
variables BATCH_COL0, BATCH_COL1, etc. are also set, yielding one variable per
column in timefile. If timefile has trailing text then that text can be accessed via the
variable BATCH_TEXT, and if word-splitting was explicitly requested by +w modifier to -
T then the trailing text is also split into individual word
parameters BATCH_WORD0, BATCH_WORD1, etc. Note: Any product(s) made by the
processing scripts should be named using BATCH_NAME as their name prefix as
these will be automatically moved up to the starting directory upon completion.

Data Files
The batch scripts will be able to find any files present in the starting directory
when batch was initiated, as well as any new files produced by mainscript or the
optional scripts set via -S. No path specification is needed to access these files. Other
files may require full paths unless their directories were already included in
the DIR_DATA setting.

Custom gmt.conf files


If you have a gmt.conf file in the top directory with your main script prior to
running batch then it will be used and shared across all the scripts created and
executed unless your scripts use -C when starting a new modern mode session. The
preferred ways of changing GMT defaults is via gmtset calls in your input scripts. Note:
Each script is run in isolation (modern) mode so trying to create a gmt.conf file via
the preflight script to be used by other scripts is futile.

Constructing the Main Script


A batch sequence is not very interesting if nothing changes between calls. For the
process to change you need to have your mainscript either access a different data set
as the job number changes, or you need to access only a varying subset of a data set,
or the processing parameters need to change, or all of the above. There are several
strategies you can use to accomplish these effects:
1. Your timefile passed to -T may list names of specific data files and you simply have
your mainscript use the relevant BATCH_TEXT or BATCH_WORD? to access the
job-specific file name.
2. You have a 3-D grid (or a stack of 2-D grids) and you want to interpolate along the
axis perpendicular to the 2-D slices (e.g., time, or it could be depth). In this situation
you will use the module grdinterpolate to have the mainscript obtain a slice for the
correct time (this may be an interpolation between two different times or depths) and
process this temporary grid file.
3. You may be creating data on the fly using gmtmath or grdmath, or perhaps
processing data slightly differently per job (using parameters in the timefile) and
computing these or the changes between jobs.
4. Use your imagination to pass whatever arguments are needed via timefile.
Technical Details
The batch module creates several hidden script files that are used in the generation of
the products (here we have left the script file extension off since it depends on the
scripting language used): batch_init (initializes variables related to the overall batch job
and includes the contents of the optional includefile), batch_preflight (optional since it
derives from -Sb and computes or prepares needed data
files), batch_postflight (optional since it derives from -Sf and processes files once all the
batch job complete), batch_job (accepts a job counter argument and processes data for
those parameters), and batch_cleanup (removes temporary files at the end of the
process). For each job, there is a separate batch_params_###### script that provides
job-specific variables (e.g., job number and anything given via -T).
The preflight and postflight scripts have access to the information in batch_init, while
the batch_job script in addition has access to the job-specific parameter file. Using the -
Q option will just produce these scripts which you can then examine. Note:
The mainscript is duplicated per job and many of these are run simultaneously on all
available cores. Multi-treaded GMT modules will therefore be limited to a single core per
call. Because we do not know how many products each batch job makes, we ensure
each job creates a unique file when it is finished. Checking for these special (and
empty) files is how batch learns that a particular job has completed and it is time to
launch another one.

Hints for Batch Makers


Composing batch jobs is relatively simple, but you have to think in terms of variables.
Examine the examples we describe. Then, start by making a single script (i.e.,
your mainscript) and identify which things should change with time (i.e., with the job
number). Create variables for these values. If they are among the listed parameters
that batch creates automatically then use those names. Unless you only require the job
number you will need to make a file that you can pass via -T. This file should then have
all the values you need, per job (i.e., per row), with values across all the columns you
need. If you need to assign various fixed variables that do not change with time, then
your mainscript will look shorter and cleaner if you offload those assignments to a
separate includefile (via -I). To test your mainscript, start by using options -Q -M to
ensure that your master job results are correct. The -M option simply runs one job of
your batch sequence (you can select which one via the -M arguments [0]). Fix any
issues with your use of variables and options until this works. You can then try to
remove -Q. We recommend you make a very short (i.e., via -T) and small batch
sequence so you don’t have to wait very long to see the result. Once things are working
you can beef up number of jobs.

Examples
We extract a subset of bathymetry for the Gulf of Guinea from the 2x2 arc minute
resolution Earth DEM and compute Gaussian filtered high-pass grids using filter widths
ranging from 10 to 200 km in steps of 10 km. When the grids are all completed we
determine the standard deviation in the result. To replicate our setup, try:

cat << EOF > pre.sh


gmt begin
gmt math -o0 -T10/200/10 T = widths.txt
gmt grdcut -R-10/20/-10/20 @earth_relief_02m -Gdata.grd
gmt end
EOF
cat << EOF > main.sh
gmt begin
gmt grdfilter data.grd -Fg\${BATCH_COL0}+h -G\${BATCH_NAME}.grd -D2
gmt end
EOF
cat << EOF > post.sh
gmt begin \${BATCH_PREFIX} pdf
gmt grdmath \${BATCH_PREFIX}_*.grd -S STD = \${BATCH_PREFIX}_std.grd
gmt grdimage \${BATCH_PREFIX}_std.grd -B -B+t"STD of Gaussians residuals" -Chot
gmt coast -Wthin,white
gmt end show
EOF
gmt batch main.sh -Sbpre.sh -Sfpost.sh -Twidths.txt -Nfilter -V -Z
Of course, the syntax of how variables are used vary according to the scripting
language. Here, we actually build the pre.sh, main.sh, and post.sh scripts on the fly,
hence we need to escape any variables (since they start with a dollar sign that we need
to be written verbatim). At the end of the execution we find 20 grids (e.g., such as
filter_07.grd), as well as the filter_std.grd file obtained by stacking all the individual
scripts and computing a standard deviation. The information needed to do all of this is
hidden from the user; the actual batch scripts that we execute are derived from the
user-provided main.sh script and batch supplies the extra machinery.
The batch module automatically manages the parallel execution loop over all jobs using
all available cores and launches new jobs as old ones complete.

As another example, we get a list of all European countries and make a simple coast
plot of each of them, placing their name in the title and the 2-character ISO code in the
upper left corner, then in postflight we combine all the individual PDFs into a single PDF
file and delete the individual files:

cat << EOF > pre.sh


gmt begin
gmt coast -E=EU+l > countries.txt
gmt end
EOF
cat << EOF > main.sh
gmt begin \${BATCH_NAME} pdf
gmt coast -R\${BATCH_WORD0}+r2 -JQ10c -Glightgray -Slightblue -B -B+t"\$
{BATCH_WORD1}" -E\${BATCH_WORD0}+gred+p0.5p
echo \${BATCH_WORD0} | gmt text -F+f16p+jTL+cTL -Gwhite -W1p
gmt end
EOF
cat << EOF > post.sh
gs -dQUIET -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=\${BATCH_PREFIX}.pdf -dBATCH \$
{BATCH_PREFIX}_*.pdf
rm -f \${BATCH_PREFIX}_*.pdf
EOF
gmt batch main.sh -Sbpre.sh -Sfpost.sh -Tcountries.txt+w"\t" -Ncountries -V -W -Zs

Here, the postflight script is not even a GMT script; it simply runs gs (Ghostscript) and
deletes what we don’t want to keep.

You might also like