The Generic Mapping Tools
Version 4.5.11
A Map-making Tutorial
by
Pål (Paul) Wessel
School of Ocean and Earth Science and Technology
University of Hawai’i at Mānoa
and
Walter H. F. Smith
Laboratory for Satellite Altimetry
NOAA/NESDIS
November 2013
The purpose of this tutorial is to introduce new users to GMT, outline the GMT environment, and enable you to make several forms of graphics without having to know too much about UNIX and UNIX tools. We will not be able to cover all aspects of GMT nor will we necessarily cover the selected topics in sufficient detail. Nevertheless, it is hoped that the exposure will prompt the users to improve their GMT and UNIX skills after completion of this short tutorial.
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. We obtained NSF-funding for GMT version 3.0 in 1993 which was released with another article in EOS on August 15, 1995. Significantly improved versions (3.1-3.3, 3.3.1–6), 3.4, 3.4.1–5, and 4.0–4.5.9 were released between November 1998 and April 2013, culminating in the November 2013 introduction of 4.5.11. GMT now is used by ten thousands of users worldwide in a broad range of disciplines.
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 programs. GMT uses architecture-independent file formats.
The price is right! Also, GMT offers unlimited flexibility since it can be called from the command line, inside scripts, and from user programs. GMT has attracted many users because of its high quality PostScript output. GMT easily installs on almost any computer.
GMT has been installed on machines ranging from super-computers to lap-top PCs. GMT only contains some 100,000 lines of code and has modest space/memory requirements. Minimum requirements are
In addition, we recommend access to a PostScript printer or equivalent (e.g., ghostscript), PostScript previewer (e.g., gv (ghostview)), any flavor of the UNIX operating system, and more disk space and memory.
To get a good grasp on GMT one must understand what is going on “under the hood”. Figure 1.1 illustrates the relationships you need to be aware of at run-time.
A GMT program may or may not take input files. Three different types of input are recognized (more details can be found in Appendix B in the Technical Reference):
You may choose among several file formats (even define your own format), but the GMT default is the architecture-indenpendent netCDF format.
GMT programs may get operational parameters from several places:
There are 6 general categories of output produced by GMT:
Note: GMT automatically creates and updates a history of past GMT command options for the common switches. This history file is called .gmtcommands and one will be created in every directory from which GMT programs are executed. Many initial problems with GMT usage result from not fully appreciating the relationships shown in Figure 1.1.
Most GMT programs 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 UNIX redirection:
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.
Sometimes we want to use the output from one program as input to another program. This is achieved with UNIX pipes:
Most UNIX and GMT programs 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
When we want to save both program output and error messages to separate files we use the following syntax:
UNIX provides several ways to select groups of files based on name patterns (Table 1.1):
Code | Meaning
|
* | Matches anything |
? | Matches any single character |
[list] | Matches characters in the list |
[range] | Matches characters in the given 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.
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 -B, -J, and -R switches and to familiarize ourselves with a few selected GMT projections. The GMT programs we will utilize are psbasemap and pscoast. Please consult their manual pages on the GMT web site for reference.
We start by making the basemap frame for a linear x-y plot. We want it to go from 10 to 70 in x, annotating every 10, and from -3 to 8 in y, annotating every 1. The final plot should be 4 by 3 inches in size. Here’s how we do it:
You can view the result with gv plot.ps.
We next will show how to do a basemap for a log–log plot. We will assume that the raw x data range from 3 to 9613 and y ranges from to . One possibility is
(The backslash makes UNIX ignore the carriage return that follows and treat the two lines as one long command).
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 pscoast which automatically will access the GMT coastline, river and border data base derived from the GSHHG database1. In addition to the common switches we may need to use some of several pscoast -specific options (see Table 1.2).
Option | Purpose
|
-A | Exclude small features or those of high hierarchical levels (see Appendix K) |
-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:
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
-JB
where () is the map (projection) center and are the two standard parallels where the cone intersects the Earth’s surface. We try the following command:
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
-JG
where () is the center of the map (projection). As an example we will try
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[fs]
where f gives Eckert IV (4) and s (Default) gives Eckert VI (6). The 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
There are 18 GMT programs that directly create (or add overlays to) plots (Table 2.1); 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 | |
psbasemap | Create an empty basemap frame with optional scale |
pscoast | Plot coastlines, filled continents, rivers, and political borders |
pslegend | Create legend overlay |
POINTS AND LINES
| |
pswiggle | Draw spatial time-series along their -tracks |
psxy | Plot symbols, polygons, and lines in 2-D |
psxyz | Plot symbols, polygons, and lines in 3-D |
HISTOGRAMS | |
pshistogram | Plot a rectangular histogram |
psrose | Plot a polar histogram(sector/rose diagram) |
CONTOURS
| |
grdcontour | Contouring of 2-D gridded data sets |
pscontour | Direct contouring or imaging of data by optimal triangulation |
SURFACES
| |
grdimage | Produce color images from 2-D gridded data |
grdvector | Plot vector fields from 2-D gridded data |
grdview | 3-D perspective imaging of 2-D gridded data |
UTILITIES
| |
psclip | Use polygon files to initiate custom clipping paths |
psimage | Plot Sun raster files |
psmask | Create clipping paths or generate overlay to mask |
psscale | Plot gray scale or color scale bar |
pstext | Plot text strings on maps |
Plotting lines and symbols, psxy is one of the most frequently used programs 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 psxy harder to master than most GMT tools. Table 2.2 shows a complete list of the options.
Option | Purpose
|
-A | Suppress line interpolation along great circles |
-Ccpt | Let symbol color be determined from -values and the cpt file |
-E[xX][yY][cap][/pen] | Draw selected error bars with specified attributes |
-Gfill | Set color for symbol or fill for polygons |
-L | Explicitly close polygons |
-N | Do Not clip symbols at map borders |
-S[symbol][size] | Select one of several symbols (See Table 2.3) |
-Wpen | Set pen for line or symbol outline |
-m[flag] | Multiple segment input data; headers start with flag |
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 Table 2.3.
Option | Symbol
|
-S-size | horizontal dash; size is length of dash |
-Sasize | star; size is radius of circumscribing circle |
-Sbsize[/base][u] | bar; size is bar width, append u if size is in x-units |
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 in inches |
are read from the input file | |
-SE | ellipse; azimuth (CW from vertical), major, and minor axes in 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/string[%font] | letter; size is fontsize. Append a letter or text string, and optionally a font |
-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 |
-Sv[thick/length/width][nnorm] | vector; direction (CCW from horizontal) and length are read from input data |
Optionally, append the thickness of the vector and the width and length of the | |
arrow-head. If the nnorm is appended, all vectors whose lengths are less than | |
norm will have their attributes scaled by length/norm | |
-SV[thick/length/width][nnorm] | vector, except azimuth (degrees east of north) is expected instead of direction |
The angle on the map is calculated based on the chosen map projection | |
-Sw[size | pie wedge; start and stop directions (CCW from horizontal) are read from |
input data | |
-Sxsize | cross; size is length of crossing lines |
-Sysize | vertical dash; size is length of dash |
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 []):
[
] [
] [
] [
] [
]
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:
Before we try some examples we need to review two key switches; they specify pen attributes and symbol or polygon fill. Please consult Chapter 4 in the GMT Technical Reference and Cookbook before experimenting with the examples below.
We will start off using the file data in your directory. Using the GMT utility minmax we find the extent of the data region:
which returns
telling us that the file data 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:
To simply plot the data as a line we choose no symbol and specify a pen thickness instead:
A common question is : “How can I plot symbols connected by a line with psxy?”. The surprising answer is that we must call psxy 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:
Our final psxy 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. You will find the two files quakes.ngdc and quakes.cpt in your directory. The first few lines in the quakes.ngdc looks like this:
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.02 will work well. Reformatting this file to comply with the psxy input format can be done in a number of ways, including manual editing, using MATLAB, a spreadsheet program, or UNIX tools. Here, without further elaboration, we simply use the UNIX tool awk to do the job ($5 refers to the 5’th column etc., and NR is the current record number):
The awk statement is automatically applied to each record, hence the output file quakes.d should now look like this (try it!):
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:
Apart from comment lines (starting with #), each record in the cpt file governs the color of a symbol whose z value falls in the range between and . If the colors for the lower and upper levels differ then an intermediate color will be linearly interpolated given the value. Here, we have chosen constant color intervals.
We may now complete our example using the Mercator projection; we throw in a map scale out of pure generosity:
where the i appended to the -Sc option ensures that symbols sizes are interpreted to be in inches.
In many situations we need to annotate plots or maps with text strings; in GMT this is done using pstext. Apart from the common switches, there are 7 options that are particularly useful (Table 2.4).
Option | Purpose
|
-Cdx/dy | Spacing between text and the text box (see -W) |
-Ddx/dy | Offsets the projected location of the strings |
-Gfill | Sets the color of the text |
-L | Lists the font ids and exits |
-N | Deactivates clipping at the borders |
-Spen | Selects outline font and sets pen attributes |
-W[fill][o[pen]] | Paint the text box; draw the outline if o is appended (also see -C) |
The input data to pstext is expected to contain the following information:
x y size angle fontno justify text
The size argument is the font size in points, the angle is the angle (measured counterclockwise) between the text’s baseline and the horizontal, justify indicates which point on the text-string should correspond to the given x, y location, and text is the text string or sentence to plot. Figure 2.2 illustrates these concepts and shows 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 in Tables 2.5 and 2.6.
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 |
@%fontno% | 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 book. For accented European characters you must set CHAR_ENCODING to ISOLatin1 in your .gmtdefaults4 file.
We will demonstrate pstext with the following script:
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. We pipe the PostScript directly through gv (the – tells gv that piping is happening).
GMT comes with several utilities that can create gridded data sets; we will discuss two such programs later this session. First, we will assume that we already have gridded data sets. In the supplemental GMT archive there is a program that serves as a data extractor from several public domain global gridded data sets. Among these data are ETOPO5, crustal ages, gravity and geoid, and DEM for the continental US. Here, we will use grdraster to extract a GMT-ready grid that we will next use for contouring:
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 find bermuda.nc also in the tutorial directory of you GMT installation. Feel free to open it in any other program and compare results with GMT.
We first use the GMT program grdinfo to see what’s in this file:
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 program 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 every x_inc/smooth increment |
-T[+-][gap/length][:LH] | Draw tick-marks in downhill direction for innermost closed contours |
Add tick spacing and length, and characters to plot at the center of closed contours. | |
-W[ac]pen | Set contour and annotation pens |
-Zfactor[/offset] | [Subtract offset] and multiply data by factor prior to 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°:
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:
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 programs have in common the requirement that the user must specify the grid domain and
output filename:
-Rxmin/xmax/ymin/ymax | The desired grid extent |
-Ixinc[mc][/yinc[mc]] | The grid spacing (append m or c for minutes or seconds of arc) |
-Ggridfile | The output grid filename |
The GMT program 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 as follows:
The most important switches are listed in Table 3.2.
Option | Purpose
|
-Sradius[k] | Sets search radius. Append k to indicate radius in kilometers [Default is x-units] |
-Eempty | Assign this value to unconstrained nodes [Default is NaN] |
-Nsectors | Sector search, indicate number of sectors [Default is 4] |
-W | Read relative weights from the 4th column of input data |
We will grid the data in the file ship.xyz which contains ship observations of bathymetry off Baja California. You can find the file in the sub-directory for example 15. We desire to make a 5’ by 5’ grid. Running minmax on the file yields
so we choose the region accordingly:
We may get a view of the contour map using
Since the grid ship.nc is stored in netCDF format that is supported by a host of other programs, you can try one of those as well on the same grid.
As an alternative, we may use a global procedure to grid our data. This approach, implemented in the program
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
that
satisfies the following constraints:
where is the “tension”, . Basically, as we obtain the minimum curvature solution, while as we go towards 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 program are indicated in Table 3.32.
Option | Purpose
|
-Aaspect | Sets aspect ratio for anisotropic grids. |
-Climit | Sets convergence limit. Default is 1/1000 of data range. |
-Ttension | Sets the tension [Default is 0] |
The surface program 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 (listed in Table 3.4).
Option | Purpose
|
-N | Choose pixel node registration [Default is gridline] |
-W[io] | Append i or o to read or write weights in the 4th column |
With respect to our ship data we preprocess it using the median method:
The output data can now be used with surface:
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:
Here we have only time to explore the latter approach. The psmask program 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 psmask. Here’s the recipe:
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
The cpt file is discussed in detail in the GMT Technical Reference and Cookbook, Chapter 4. Please review the format before experimenting further.
Cpt files can be created in any number of ways. GMT provides two mechanisms:
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 program with no arguments) and the equidistant -values to go with it. The main options are given below.
Option | Purpose
|
-C | Set the name of the master cpt file 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 cpt files for data that ranges from -20 to 60, with color changes at every 10, try these two variants:
We can plot these color tables with psscale; the options worth mentioning here are listed in Table 4.2. 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 colorbars.)
Option | Purpose
|
-Ccptfile | The required cpt file |
-Dxpos/ypos/length/width[h] | Sets the position of the center/left and dimensions of scale bar. |
Append h to get horizontal bar and give center/top instead | |
-Imax_intensity | Add illumination effects |
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 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.
Once a cpt file 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 (data id 9) from USGS:
You can find the grid us.nc also in the tutorial directory of your GMT installation. Using grdinfo we find that the data ranges from 1000m to 4300m so we make a cpt file accordingly:
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 cptfile; the main other options are
Option | Purpose
|
-Edpi | Sets the desired resolution of the image [Default is data resolution] |
-Iintenfile | Use artificial illumination using intensities from intensfile |
-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
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 | Purpose
|
-Aazimuth | Azimuthal direction for gradients |
-M | Indicates that this is a geographic grid |
-N[te][norm[/offset]] | Normalize gradients by norm/offset [= 1/0 by default]. |
Insert t to normalize by the transformation. | |
Insert e to normalize by the cumulative Laplace distribution. | |
Figure 4.1 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 ±1 range; horizontal arrow pointing to the y-value).
Both -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
Given the cpt file and the two gridded data sets we can create the shaded relief image:
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 “horizonal” 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.
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.
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). We do this as follows:
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:
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.
Our final undertaking in this tutorial is to examine three-dimensional perspective views. GMT is currently limited to vantage points at infinity; thus we are unable to do fly-by’s through canyons etc. The GMT module that produces perspective views of gridded data files is grdview. It can make two kinds of plots:
Regardless of plot type, some arguments must be specified; these are
In addition, some options may be required:
Option | Purpose
|
-Ccptfile | The cptfile is required for color -coded surfaces and for contoured mesh plots |
-Gdrape_file | Assign colors using drape_file instead of relief_file |
-Iintens_file | File with illumination intensities |
-Qm | Selects mesh plot |
-Qs[m] | Surface plot using polygons; append m to show mesh. This option allows for -W |
-Qidpi[g] | Image by scan-line conversion. Specify dpi; append g to force gray-shade image. -B is disabled. |
-Wpen | Draw contours on top of surface (except with -Qi) |
Mesh plots work best on smaller data sets. We again use the small subset of the ETOPO5 data over Bermuda and make a quick-and-dirty cpt file:
A simple mesh plot can therefore be obtained with
We will make a perspective, color-coded view of the US Rockies from the southeast. This is done using
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.