1.. _GMT_General_Features:
2
3General Features
4================
5
6This section explains features common to all the programs in GMT and
7summarizes the philosophy behind the system. Some of the features
8described here may make more sense once you reach the cook-book section
9where we present actual examples of their use.
10
11GMT Modern Mode Hierarchical Levels
12-----------------------------------
13
14As you read below of how we handle default settings, command-line history, and
15color tables, it is important to understand that under GMT **modern mode** we
16maintain several *levels* of these parameters.  As you will see later, this affects
17*three* aspects of GMT: The chosen default settings, the current history of
18previous common option arguments, and the current color table.  All three items
19are given a consistent treatment in GMT modern mode (in classic mode there is
20only a single level and no concept of a current color table). Below, *item* refers
21to any of those three aspects.
22
23#. The top level is the *session*.  Any item set here is accessible to all other
24   levels.
25
26#. The next level is the *figure* level.  A session may create numerous figures
27   and items determined at this level are only accessible to that figure and
28   plot constructs below it (like subplots).
29
30#. A figure may include a *subplot*.  Before any panels are started, any
31   items determined at this level apply to *all* the panels in the subplot.
32   For instance, setting a new color table will apply to all the panels that
33   need it.
34
35#. Once you start a specific *panel* in a subplot, any items determined at this
36   level only apply to that panel.  For instance, changing the font used for
37   frame annotations for this panel is not affecting any other panels.
38
39#. Figures or panels may include a map *inset*.  Any items determined in an
40   inset is private to that inset and does not affect the higher levels.
41
42There is a distinction between *setting* an item (e.g., a font choice, an option
43like plot region, or a color table) and *getting* that item.  When we *specify*
44a particular item it is recorded at that level.  When we need to *access*
45that item, there may or may not be an item at the current hierarchical level.
46If there is not, we look at the level above the current level to see if it has
47the required item, and this search may go all the way back to the session level.
48In other words, we always give preference to items set at or just above the
49current hierarchical level as possible.  If no such item is found anywhere then
50we use the GMT defaults or color table, or we must terminate with an error if a
51required setting such as a region cannot be determined from your options or data sets.
52
53Discussions below on GMT defaults and history are presented as they apply to
54classic mode, but under modern mode these files are maintained at the levels we
55just discussed.
56
57GMT units
58---------
59
60While GMT has default units for both actual Earth distances and plot
61lengths (i.e., dimensions) of maps, it is recommended that you explicitly
62indicate the units of your arguments by appending the unit character, as
63discussed below. This will aid you in debugging, let others understand your
64scripts, and remove any uncertainty as to what unit you thought you wanted.
65
66.. _plt-units:
67
68Dimension units
69~~~~~~~~~~~~~~~
70
71GMT programs accept plot dimensional quantities (widths, offsets, etc.) in
72**c**\ m, **i**\ nch, or **p**\ oint (1/72 of an inch) [8]_. There are
73two ways to ensure that GMT understands which unit you intend to use:
74
75#. Append the desired unit to the dimension you supply. This way is
76   explicit and clearly communicates what you intend, e.g.,
77   **-JM**\ 10\ **c** means the map width being passed to the **-JM** switch
78   is 10 cm, and modifier **+o**\ 24p means we are offsetting a feature
79   by 24 points from its initial location.
80
81#. Set the parameter :term:`PROJ_LENGTH_UNIT` to the desired unit. Then,
82   all dimensions without explicit units will be interpreted accordingly.
83   By default, GMT always initializes :term:`PROJ_LENGTH_UNIT` to cm and
84   interprets unitless dimensional values as cm, except for fonts and pen
85   thicknesses which are by default interpreted as points.
86
87The latter method is less robust as other users may have a different
88default unit set and then your script may not work as intended. For portability,
89we therefore recommend you always append the desired unit explicitly.
90
91.. _dist-units:
92
93Distance units
94~~~~~~~~~~~~~~
95
96.. _tbl-distunits:
97
98+---------+-------------------+---------+------------------+
99+=========+===================+=========+==================+
100| **d**   | Degree of arc     | **M**   | Statute mile     |
101+---------+-------------------+---------+------------------+
102| **e**   | Meter [Default]   | **n**   | Nautical mile    |
103+---------+-------------------+---------+------------------+
104| **f**   | Foot              | **s**   | Second of arc    |
105+---------+-------------------+---------+------------------+
106| **k**   | Kilometer         | **u**   | US Survey foot   |
107+---------+-------------------+---------+------------------+
108| **m**   | Minute of arc     |         |                  |
109+---------+-------------------+---------+------------------+
110
111For Cartesian data the data units do not normally matter
112(they could be kg or Lumens for all we know) and are never entered.
113Geographic data are different, as distances can be specified in a variety
114of ways. GMT programs that accept actual Earth length scales like
115search radii or distances can therefore handle a variety of units. These
116choices are listed in the Table :ref:`Distance Units <tbl-distunits>`;
117simply append the desired unit to the distance value you supply. A value
118without a unit suffix will be consider to be in meters. For example, a distance
119of 30 nautical miles should be given as 30\ **n**.
120
121Distance calculations
122~~~~~~~~~~~~~~~~~~~~~
123
124The calculation of distances on Earth (or other planetary bodies)
125depends on the ellipsoidal parameters of the body (via
126:term:`PROJ_ELLIPSOID`) and the method of computation. GMT offers three
127alternatives that trade off accuracy and computation time.
128
129Flat Earth distances
130^^^^^^^^^^^^^^^^^^^^
131
132Quick, but approximate "Flat Earth" calculations make a first-order
133correction for the spherical nature of a planetary body by computing the
134distance between two points A and B as
135
136.. math::
137
138	 d_f = R \sqrt{(\theta_A - \theta_B)^2 + (\cos \left [ \frac{\theta_A +
139	 \theta_B}{2} \right ] \Delta \lambda)^2}, \label{eq:flatearth}
140
141where *R* is the representative (or spherical) radius of the
142planet, :math:`\theta` is latitude, and the difference in longitudes,
143:math:`\Delta \lambda = \lambda_A - \lambda_B`, is adjusted for any
144jumps that might occur across Greenwich or the Dateline. As written, the
145geographic coordinates are given in radians. This approach is suitable
146when the points you use to compute :math:`d_f` do not greatly differ in
147latitude and computation speed is paramount. You can select this mode
148of computation by specifying the common GMT option **-j** and appending the directive
149**f** (for Flat Earth).  For instance, a search radius of 50 statute miles
150using this mode of computation might be specified via **-S**\ 50\ **M** **-jf**.
151
152Great circle distances
153^^^^^^^^^^^^^^^^^^^^^^
154
155This is the default distance calculation, which will also approximate
156the planetary body by a sphere of mean radius *R*. However, we
157compute an exact distance between two points A and B on such a sphere
158via the Haversine equation
159
160.. math::
161
162	 d_g = 2R \sin^{-1}  {\sqrt{\sin^2\frac{\theta_A - \theta_B}{2} + \cos
163	 \theta_A \cos \theta_B \sin^2 \frac{\lambda_A - \lambda_B}{2}} },
164	 \label{eq:greatcircle}
165
166This approach is suitable for most situations unless exact calculations
167for an ellipsoid is required (typically for a limited surface area). For
168instance, a search radius of 5000 feet using this mode of computation
169would be specified as **-S**\ 5000\ **f**.
170
171**Note**: There are two additional GMT defaults that control how
172great circle (and Flat Earth) distances are computed. One concerns the
173selection of the "mean radius". This is selected by
174:term:`PROJ_MEAN_RADIUS`, which selects one of several possible
175representative radii. The second is :term:`PROJ_AUX_LATITUDE`, which
176converts geodetic latitudes into one of several possible auxiliary
177latitudes that are better suited for the spherical approximation. While
178both settings have default values to best approximate geodesic distances
179(*authalic* mean radius and latitudes), expert users can choose from a
180range of options as detailed in the :doc:`/gmt.conf` man page.  Note that
181these last two settings are only used if the :term:`PROJ_ELLIPSOID`
182is not set to "sphere".
183
184Geodesic distances
185^^^^^^^^^^^^^^^^^^
186
187For the most accurate calculations we use a full ellipsoidal
188formulation. Currently, we are using Vincenty's [1975] formula [7]_
189which is accurate to 0.5 mm. You
190select this mode of computation by using the common GMT option **-j**
191and appending the directive **e** (for ellipsoidal).
192For instance, a search radius of 20 km using this mode of
193computation would be set by **-S**\ 20\ **k** **-je**.  You may use the
194setting :term:`PROJ_GEODESIC` which defaults to
195*Vincenty* but may also be set to *Rudoe* for old GMT4-style calculations
196or *Andoyer* for an approximate geodesic (within a few tens of meters)
197that is much faster to compute.
198
199GMT defaults
200------------
201
202Overview and the gmt.conf file
203~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
204
205There are almost 150 parameters which can be adjusted individually to
206modify the appearance of plots or affect the manipulation of data. When
207a new session starts (unless **-C** is given), it initializes all parameters to the
208GMT defaults [9]_, then tries to open the file ``gmt.conf`` in the current
209directory [10]_. If not found, it will look for that file in a
210sub-directory ``/.gmt`` of your home directory, and finally in your home directory
211itself. If successful, the session will read the contents and set the
212default values to those provided in the file. By editing this file you
213can affect features such as pen thicknesses used for maps, fonts and
214font sizes used for annotations and labels, color of the pens,
215dots-per-inch resolution of the hardcopy device, what type of spline
216interpolant to use, and many other choices. A complete list of all the
217parameters and their default values can be found in the
218:doc:`/gmt.conf` manual pages. Figures
219:ref:`GMT Parameters a <gmt_defaults_a>`,
220:ref:`b <gmt_defaults_b>`, and
221:ref:`c <gmt_defaults_c>` show the parameters that affect
222plots. You may create your own ``gmt.conf`` files by running
223:doc:`/gmtdefaults` and then modify those
224parameters you want to change. If you want to use the parameter settings
225in another file you can do so by copying that file to the current
226directory and call it gmt.conf. This makes it easy to maintain several distinct parameter
227settings, corresponding perhaps to the unique styles required by
228different journals or simply reflecting font changes necessary to make
229readable overheads and slides.  At the end of such scripts you should then
230delete the (temporary) gmt.conf file.  Note that any arguments given on the
231command line (see below) will take precedent over the default values.
232E.g., if your ``gmt.conf`` file has *x* offset = 3\ **c** as default, the
233**-X**\ 5\ **c** option will override the default and set the offset to 5 cm.
234
235.. _gmt_defaults_a:
236
237.. figure:: /_images/GMT_Defaults_1a.*
238   :width: 500 px
239   :align: center
240
241   Some GMT parameters that affect plot appearance.
242
243.. toggle::
244
245   Here is the source script for the figure above:
246
247   .. literalinclude:: /_verbatim/GMT_Defaults_1a.txt
248
249
250.. _gmt_defaults_b:
251
252.. figure:: /_images/GMT_Defaults_1b.*
253   :width: 500 px
254   :align: center
255
256   More GMT parameters that affect plot appearance.
257
258.. toggle::
259
260   Here is the source script for the figure above:
261
262   .. literalinclude:: /_verbatim/GMT_Defaults_1b.txt
263
264.. _gmt_defaults_c:
265
266.. figure:: /_images/GMT_Defaults_1c.*
267   :width: 500 px
268   :align: center
269
270   Even more GMT parameters that affect plot appearance.
271
272.. toggle::
273
274   Here is the source script for the figure above:
275
276   .. literalinclude:: /_verbatim/GMT_Defaults_1c.txt
277
278There are at least two good reasons why the GMT default options are
279placed in a separate parameter file:
280
281#. It would not be practical to allow for command-line syntax covering
282   so many options, many of which are rarely or never changed (such as
283   the ellipsoid used for map projections).
284
285#. It is convenient to keep separate ``gmt.conf`` files for specific projects, so
286   that one may achieve a special effect simply by running
287   GMT commands in the directory whose ``gmt.conf`` file has the desired settings.
288   For example, when making final illustrations for a journal article
289   one must often standardize on font sizes and font types, etc. Keeping
290   all those settings in a separate ``gmt.conf`` file simplifies this process and
291   will allow you to generate those illustrations with the same settings
292   later on. Likewise, GMT scripts that make figures for PowerPoint
293   presentations often use a different color scheme and font size than
294   output intended for laser printers. Organizing these various
295   scenarios into separate ``gmt.conf`` files will minimize headaches associated with
296   micro-editing of illustrations.
297
298
299.. _auto-scaling:
300
301Automatic GMT settings
302~~~~~~~~~~~~~~~~~~~~~~
303
304The **auto** flag for :doc:`GMT parameters </gmt.conf>` signals that suitable
305dimensions or settings will be automatically computed when the plot dimensions
306are known. The **auto** flag is supported for the following parameters:
307
308================================== ===============================================
309:term:`FONT_ANNOT_PRIMARY`         Primary annotation font [11.00p]
310:term:`FONT_ANNOT_SECONDARY`       Secondary annotation font [13.20p]
311:term:`FONT_HEADING`               Subplot heading font [30.80p]
312:term:`FONT_LABEL`                 Axis label font [15.40p]
313:term:`FONT_LOGO`                  Logo font [8.80p]
314:term:`FONT_SUBTITLE`              Plot subtitle font [19.80p]
315:term:`FONT_TAG`                   Tag/labeling font [17.60p]
316:term:`FONT_TITLE`                 Plot title font [24.20p]
317:term:`MAP_ANNOT_MIN_SPACING`      Minimum space between annotations [11.00p]
318:term:`MAP_ANNOT_OFFSET_PRIMARY`   Primary annotation offset from axis [3.30p]
319:term:`MAP_ANNOT_OFFSET_SECONDARY` Secondary annotation offset from axis [3.30p]
320:term:`MAP_FRAME_AXES`             Axes that are drawn and annotated
321:term:`MAP_FRAME_PEN`              Pen width of plain frame [1.65p]
322:term:`MAP_FRAME_WIDTH`            Width of fancy frame [3.30p]
323:term:`MAP_GRID_PEN_PRIMARY`       Pen width of primary gridline [0.28p]
324:term:`MAP_GRID_PEN_SECONDARY`     Pen width of secondary gridline [0.55p]
325:term:`MAP_HEADING_OFFSET`         Heading offset from subplot [17.60p]
326:term:`MAP_LABEL_OFFSET`           Label offset from annotations [6.60p]
327:term:`MAP_POLAR_CAP`              Appearance of gridlines near the poles
328:term:`MAP_TICK_LENGTH_PRIMARY`    Length of primary tick marks [2.2p/1.1p]
329:term:`MAP_TICK_LENGTH_SECONDARY`  Length of secondary tick marks [6.60p/1.65p]
330:term:`MAP_TICK_PEN_PRIMARY`       Pen width of primary tick marks [0.55p]
331:term:`MAP_TICK_PEN_SECONDARY`     Pen width of secondary tick marks [0.28p]
332:term:`MAP_TITLE_OFFSET`           Title offset from plot [13.20p]
333================================== ===============================================
334
335The reference dimensions listed in brackets are the values for a plot
336with a height and width of 25 cm.  Larger and smaller illustrations
337will see a linear magnification or attenuation of these dimensions. The primary
338annotation font size will be computed as::
339
340    size = (2/15) * (map_size_in_cm - 10) + 9 [in points]
341
342where :math:`map\_size\_in\_cm = sqrt(map\_height  x  map\_width)`.  All other
343items will have their reference sizes scaled by :math:`scale = size / 10`. In
344modern mode, if you do nothing then all of the above dimensions will be
345automatically set based on your plot dimensions.  However, you are free to
346override any of them using the methods described in the next section. **Note**:
347Selecting **auto** for font sizes and dimensions requires GMT to know the plot
348dimensions. If the plot dimensions are not available (e.g., :doc:`/pslegend`
349with **-Dx** and no **-R -J**), the settings will be updated using the nominal
350font sizes and dimensions for a 10 x 1 cm plot. **Note**: The particular scaling
351relationship is experimental in 6.2 and we reserve the right to adjust it
352pending further experimentation and user feedback.
353
354For **MAP_POLAR_CAP**, **auto** will determine a suitable *pc_lat* for your
355region for all azimuthal projections and a few others in which the geographic
356poles are plotted as points (Lambert Conic, Oblique Mercator, Hammer, Mollweide,
357Sinusoidal, and van der Grinten).
358
359For **MAP_FRAME_AXES**, **auto** will determine a suitable setting based on the
360projection, type of plot, perspective, etc. For example, GMT will determine the
361position of different quadrants for perspective and polar plots and select the
362equivalent of **WrStZ**. The default for the Gnomonic and general perspective
363projections is **WESNZ**. The default for non-perspective, non-Gnomonic, and
364non-polar plots using **MAP_FRAME_AXES**\ =\ **auto** is **WrStZ**.
365
366For **MAP_LABEL_OFFSET, **auto** will scale the offset based on figure size if
367**MAP_LABEL_MODE** is set to **annot**, but will default to **32p** if
368**MAP_LABEL_MODE** is set to **axis**.
369
370Changing GMT defaults
371~~~~~~~~~~~~~~~~~~~~~
372
373As mentioned, GMT programs will attempt to open a file named  ``gmt.conf``. At
374times it may be desirable to override that default. There are several
375ways in which this can be accomplished.
376
377*  One method is to start each script by saving a copy of the current  ``gmt.conf``,
378   then copying the desired ``gmt.conf`` file to the current directory, and finally
379   reverting the changes at the end of the script. Possible side effects
380   include premature ending of the script due to user error or bugs
381   which means the final resetting does not take place (unless you write
382   your script very carefully.)
383
384*  To permanently change some of the GMT parameters on the fly
385   inside a script the :doc:`/gmtset` utility
386   can be used. E.g., to change the primary annotation font to 12 point
387   Times-Bold in red we run
388
389   ::
390
391    gmt set FONT_ANNOT_PRIMARY 12p,Times-Bold,red
392
393   These changes will remain in effect until they are overridden.
394
395*  If all you want to achieve is to change a few parameters during the
396   execution of a single command but otherwise leave the environment
397   intact, consider passing the parameter changes on the command line
398   via the **-**\ **-**\ *PAR=value* mechanism. For instance, to temporarily
399   set the output format for floating points to have lots of decimals,
400   say, for map projection coordinate output, append
401   **-**\ **-**\ :term:`FORMAT_FLOAT_OUT`\ =%.16lg to the command in question.
402
403In addition to those parameters that directly affect the plot there are
404numerous parameters than modify units, scales, etc. For a complete
405listing, see the :doc:`/gmt.conf` man pages.
406We suggest that you go through all the available parameters at least
407once so that you know what is available to change via one of the
408described mechanisms.  The gmt.conf file can be cleared by running
409**gmt clear settings**.
410
411Command line arguments
412----------------------
413
414Each program requires certain arguments specific to its operation. These
415are explained in the manual pages and in the usage messages.
416We have tried to choose letters of the alphabet which
417stand for the argument so that they will be easy to remember. Each
418argument specification begins with a hyphen (except input file names;
419see below), followed by a letter, and sometimes a number or character
420string immediately after the letter. *Do not* space between the hyphen,
421letter, and number or string. *Do* space between options. Example:
422
423   ::
424
425    gmt coast -R0/20/0/20 -Ggray -JM15c -Wthin -Baf -V -pdf map
426
427Command line history
428--------------------
429
430GMT programs "remember" the standardized command line options (See
431Chapter :doc:`options`) given during their first invocations in a modern
432mode session, and afterwards we do not need to repeat them any further.
433For example, if a map was created with an Cartesian linear projection,
434then any subsequent :doc:`/plot` commands to plot symbols on the same map
435do not need to repeat the region and projection information, as shown here::
436
437     gmt begin map
438       gmt basemap -R0/6.5/0/7 -Jx2c -B
439       gmt plot @Table_5_11.txt -Sc0.3c -Gred
440     gmt end show
441
442Thus, the chosen options remain in effect until you provide new option
443arguments on the command line.  **Note**: We keep track of two types of regions,
444One is the domain used for a map and one is the domain used for processing,
445which often are the same.  When a plot is specified without providing
446a region then we look for a previous plot region in the history first, and
447if it is not found then we look for the processing domain to use instead.  However,
448if a data-processing module is not given a region then we only look
449for a previous processing domain; we never substitute a plot domain in that case.
450
451Usage messages, syntax- and general error messages
452--------------------------------------------------
453
454Each program carries a usage message. If you enter the program name
455without any arguments, the program will write the complete usage message
456to standard error (your screen, unless you redirect it). This message
457explains in detail what all the valid arguments are. If you enter the
458program name followed by a *hyphen* (-) only you will get a shorter
459version which only shows the command line syntax and no detailed
460explanations. If you incorrectly specify an option or omit a required
461option, the program will produce syntax errors and explain what the
462correct syntax for these options should be. If an error occurs during
463the running of a program, the program will in some cases recognize this
464and give you an error message. Usually this will also terminate the run.
465The error messages generally begin with the name of the program in which
466the error occurred; if you have several programs piped together this
467tells you where the trouble is.
468
469Standard input or file, header records
470--------------------------------------
471
472Most of the programs which expect table data input can read either
473standard input or input in one or several files. These programs will try
474to read *stdin* unless you type the filename(s) on the command line
475without the above hyphens. (If the program sees a hyphen, it reads the
476next character as an instruction; if an argument begins without a
477hyphen, it tries to open this argument as a filename).  This feature
478allows you to connect programs with pipes if you like.
479To give numerous input files you can either list them all (file1.txt file2.txt ...),
480use UNIX wild cards (file*.txt), or make a simple *listfile* with the
481names of all your datafiles (one per line) and then use the special
482=\ *filelist* mechanism to specify the input files to a module.
483This allows GMT modules to obtain the input file names from *filelist*.
484If your input is
485ASCII and has one or more header records that do not begin with #, you
486must use the **-h** option (see Section :ref:`option_-h`).
487ASCII files may in many cases also contain segment-headers
488separating data segments. These are called "multi-segment files". For
489binary table data the **-h** option may specify how many bytes should be
490skipped before the data section is reached. Binary files may also
491contain segment-headers separating data segments. These segment-headers
492are simply data records whose fields are all set to NaN; see Chapter
493:doc:`file-formats` for complete documentation.
494
495If filenames are given for reading, GMT programs will first look for
496them in the current directory. If the file is not found, the programs
497will look in other directories pointed to by the
498:ref:`directory parameters <DIR Parameters>` :term:`DIR_DATA` and :term:`DIR_CACHE`
499or by the environmental parameters **$GMT_USERDIR**, **$GMT_CACHEDIR** and
500**$GMT_DATADIR** (if set). They may be set by the user to point to
501directories that contain data sets of general use, thus eliminating the
502need to specify a full path to these files. Usually, the :term:`DIR_DATA`
503directory will hold data sets of a general nature (tables, grids),
504whereas the **$GMT_USERDIR** directory (its default value is $HOME/.gmt)
505may hold miscellaneous data sets more specific to the user; this directory
506also stores GMT defaults, other configuration files and modern session directories as well as the
507directory *server* which olds downloaded data sets from the GMT data server
508The :term:`DIR_CACHE` will typically contain other data files
509downloaded when running tutorial or example scripts.  See :ref:`directory parameters <DIR Parameters>`
510for details. Program output is always written to the current directory
511unless a full path has been specified.
512
513URLs and remote files
514---------------------
515
516Three classes of files are given special treatment in GMT.
517
518#. Some data sets are ubiquitous and used by nearly all GMT users.
519   At the moment this collection is limited to Earth relief grids.  If you specify
520   a grid input named **@earth_relief_**\ *res* on a command line then
521   such a grid will automatically be downloaded from the GMT Data Server and placed
522   in the *server* directory under **$GMT_USERDIR** [~/.gmt].  The resolution *res* allows a choice among
523   15 common grid spacings: 01d, 30m, 20m, 15m, 10m, 06m, 05m, 04m, 03m, 02m, 01m,
524   30s, and 15s (with file sizes 111 kb, 376 kb, 782 kb, 1.3 Mb, 2.8 Mb, 7.5 Mb,
525   11 Mb, 16 Mb, 27 Mb, 58 Mb, 214 Mb, 778 Mb, and 2.6 Gb respectively) as well
526   as the SRTM tile resolutions 03s and 01s (6.8 Gb and 41 Gb for the whole set, respectively). Once
527   one of these grids have been downloaded any future reference will simply obtain the
528   file from **$GMT_USERDIR** (except if explicitly removed by the user).
529   **Note**: The 15 arc-sec data comes from the original dataset SRTM15+.
530   Lower resolutions are spherically Gaussian-filtered versions of SRTM15+.
531   The SRTM (version 3) 1 and 3 arc-sec tiles are only available over land
532   between 60 degrees south and north latitude and are stored as highly compressed JPEG2000
533   tiles on the GMT server.  These are individually downloaded as requested, converted to netCDF
534   grids and stored in subdirectories srtm1 and srtm3 under the server directory, and assembled
535   into a seamless grid using :doc:`/grdblend`. A tile is only downloaded and converted
536   once (unless the user cleans the data directories).
537#. If a file is given as a full URL, starting with **http://**, **https://**,
538   or **ftp://**, then the file will be downloaded to the current directory and subsequently
539   read from there (until removed by the user).  If the URL is actually a CGI Get
540   command (i.e., ends in ?par=val1&par2=val2...) then we download the file
541   each time we encounter the URL.
542#. Demonstration files used in online documentation, example scripts, or even the
543   large test suite may be given in the format @\ *filename*.  When such a file is
544   encountered on the command line it is understood to be a short-hand representation
545   of the full URL to *filename* on the GMT Cache Data site.
546   Since this address may change over time we use the leading
547   @ to simplify access to these files.  Such files will also be downloaded
548   to :term:`DIR_CACHE` and subsequently read from there (until removed by the user).
549#. By default, remote files are downloaded from the SOEST data server.  However, you
550   can override that selection by setting the environmental parameter **$GMT_DATA_SERVER** or
551   the default setting for :term:`GMT_DATA_SERVER`.  Alternatively, configure the CMake
552   parameter GMT_DATA_SERVER at compile time.
553#. If your Internet connection is slow or nonexistent (e.g., on a plane) you can also
554   limit the size of the largest datafile to download via :term:`GMT_DATA_SERVER_LIMIT` or
555   you can temporarily turn off such downloads by setting :term:`GMT_DATA_UPDATE_INTERVAL` to "off".
556
557The user cache (:term:`DIR_CACHE`) and all its contents can be cleared any time
558via the command **gmt clear cache**, while the server directory with downloaded data
559can be cleared via the command **gmt clear data**.  Finally, when a remote file is requested
560we also check if that file has changed at the server and re-download the updated file;
561this check is only performed no more often than once a day.
562
563.. figure:: /_images/GMT_SRTM.*
564   :width: 700 px
565   :align: center
566
567   The 14297 1x1 degree tiles (red) for which SRTM 1 and 3 arc second data are available.
568
569.. toggle::
570
571   Here is the source script for the figure above:
572
573   .. literalinclude:: /_verbatim/GMT_SRTM.txt
574
575As a short example, we can make a quick map of Easter Island using the SRTM 1x1 arc second
576grid via
577
578::
579
580 gmt grdimage -R109:30W/109:12W/27:14S/27:02S -JM15c -B @earth_relief_01s -png easter
581
582Verbose operation
583-----------------
584
585Most of the programs take an optional **-V** argument which will run the
586program in the "verbose" mode (see Section :ref:`option_-V`).
587Verbose will write to standard error information about the
588progress of the operation you are running. Verbose reports things such
589as counts of points read, names of data files processed, convergence of
590iterative solutions, and the like. Since these messages are written to
591*stderr*, the verbose talk remains separate from your data output. You
592may optionally choose among six models of *verbosity*; each mode adds
593more messages with an increasing level of details. The modes are
594
595  - **q** - Quiet, not even fatal error messages are produced.
596  - **e** - Error messages only.
597  - **w** - Warnings (same as running without **-V**)
598  - **t** - Timings (report runtimes for time-intensive algorithms).
599  - **i** - Informational messages (same as **-V** only).
600  - **c** - Compatibility warnings (if compiled with backward-compatibility).
601  - **d** - Debugging messages (mostly of interest to developers).
602
603The verbosity is cumulative, i.e., mode **w** means all messages of mode
604**e** as well will be reported.
605
606Program output
607--------------
608
609Most programs write their results, including PostScript plots, to
610standard output. The exceptions are those which may create binary netCDF
611grid files such as :doc:`/surface` (due to the
612design of netCDF a filename must be provided; however, alternative
613binary output formats allowing piping are available; see Section
614:ref:`grid-file-format`).
615Most operating systems let you can redirect
616standard output to a file or pipe it into another process. Error
617messages, usage messages, and verbose comments are written to standard
618error in all cases. You can usually redirect standard error as well, if
619you want to create a log file of what you are doing. The syntax for
620redirection differ among the main shells (Bash and C-shell) and is a bit
621limited in DOS.
622
623.. _input-data-formats:
624
625Input data formats
626------------------
627
628Most of the time, GMT will know what kind of *x* and *y*
629coordinates it is reading because you have selected a particular
630coordinate transformation or map projection. However, there may be times
631when you must explicitly specify what you are providing as input using
632the **-f** switch. When binary input data are expected (**-bi**) you
633must specify exactly the format of the records. However, for ASCII input
634there are numerous ways to encode data coordinates (which may be
635separated by white-space or commas). Valid input data are generally of
636the same form as the arguments to the **-R** option (see
637Section :ref:`option_-R`), with additional flexibility for calendar data.
638Geographical coordinates, for example, can be given in decimal degrees
639(e.g., -123.45417) or in the
640[±]\ *ddd*\ [:*mm*\ [:*ss*\ [*.xxx*]]][**W**\|\ **E**\|\ **S**\|\ **N**]
641format (e.g., 123:27:15W). With **-fp** you may even supply projected
642data like UTM coordinates.
643
644Because of the widespread use of incompatible and ambiguous formats, the
645processing of input date components is guided by the template
646:term:`FORMAT_DATE_IN` in your :doc:`/gmt.conf` file; it is by default set to *yyyy-mm-dd*.
647Y2K-challenged input data such as 29/05/89 can be processed by setting
648:term:`FORMAT_DATE_IN` to dd/mm/yy. A complete description of possible
649formats is given in the :doc:`/gmt.conf` man
650page. The *clock* string is more standardized but issues like 12- or
65124-hour clocks complicate matters as well as the presence or absence of
652delimiters between fields. Thus, the processing of input clock
653coordinates is guided by the template :term:`FORMAT_CLOCK_IN` which
654defaults to *hh:mm:ss.xxx*.
655
656GMT programs that require a map projection argument will implicitly
657know what kind of data to expect, and the input processing is done
658accordingly. However, some programs that simply report on minimum and
659maximum values or just do a reformatting of the data will in general not
660know what to expect, and furthermore there is no way for the programs to
661know what kind of data other columns (beyond the leading *x* and
662*y* columns) contain. In such instances we must explicitly tell
663GMT that we are feeding it data in the specific geographic or calendar
664formats (floating point data are assumed by default). We specify the
665data type via the **-f** option (which sets both input and output
666formats; use **-fi** and **-fo** to set input and output separately).
667For instance, to specify that the the first two columns are longitude
668and latitude, and that the third column (e.g., *z*) is absolute
669calendar time, we add **-fi**\ 0x,1y,2T to the command line. For more
670details, see the man page for the program you need to use.
671
672.. _output-data-formats:
673
674Output data formats
675-------------------
676
677The numerical output from GMT programs can be binary (when **-bo** is
678used) or ASCII [Default]. In the latter case the issue of formatting
679becomes important. GMT provides extensive machinery for allowing just
680about any imaginable format to be used on output. Analogous to the
681processing of input data, several templates guide the formatting
682process. These are :term:`FORMAT_DATE_OUT` and :term:`FORMAT_CLOCK_OUT` for
683calendar-time coordinates, :term:`FORMAT_GEO_OUT` for geographical
684coordinates, and :term:`FORMAT_FLOAT_OUT` for generic floating point data.
685In addition, the user have control over how columns are separated via
686the :term:`IO_COL_SEPARATOR` parameter. Thus, as an example, it is possible
687to create limited FORTRAN-style card records by setting
688:term:`FORMAT_FLOAT_OUT` to %7.3lf and :term:`IO_COL_SEPARATOR` to none
689[Default is tab].
690
691PostScript features
692---------------------
693
694PostScript is a command language for driving graphics devices such as
695laser printers. It is ASCII text which you can read and edit as you wish
696(assuming you have some knowledge of the syntax). We prefer this to
697binary metafile plot systems since such files cannot easily be modified
698after they have been created. GMT programs also write many comments to
699the plot file which make it easier for users to orient themselves should
700they need to edit the file (e.g., % Start of x-axis) [16]_. All
701GMT programs create PostScript code by calling the :doc:`PSL </devdocs/postscriptlight>` plot
702library (The user may call these functions from his/her own C or FORTRAN
703plot programs. See the manual pages for :doc:`PSL </devdocs/postscriptlight>` syntax). Although
704GMT programs can create very individualized plot code, there will
705always be cases not covered by these programs. Some knowledge of
706PostScript will enable the user to add such features directly into the
707plot file. By default, GMT will produce freeform PostScript output
708with embedded printer directives. To produce Encapsulated
709PostScript (EPS) that can be imported into graphics programs such as
710**CorelDraw**, **Illustrator** or **InkScape** for further
711embellishment, simply run gmt :doc:`/psconvert`
712**-Te**. See Chapter :doc:`include-figures` for an extensive discussion of converting
713PostScript to other formats.
714
715.. _-Wpen_attrib:
716
717Specifying pen attributes
718-------------------------
719
720A pen in GMT has three attributes: *width*, *color*, and
721*style*. Most programs will accept pen attributes in the form of an
722option argument, with commas separating the given attributes, e.g.,
723
724**-W**\ [*width*\ [**c**\|\ **i**\|\ **p**]],[*color*],[*style*\ [**c**\|\ **i**\|\ **p**]]
725
726    *Width* is by default measured in points (1/72 of an inch). Append
727    **c**, **i**, or **p** to specify pen width in cm, inch, or points,
728    respectively. Minimum-thickness pens can be achieved by giving zero
729    width. The result is device-dependent but typically means that as
730    you zoom in on the feature in a display, the line thickness stays
731    at the minimum. Finally, a few predefined
732    pen names can be used: default, faint, and {thin, thick,
733    fat}[er\|\ est], and wide. Table :ref:`pennames <tbl-pennames>` shows this
734    list and the corresponding pen widths.
735
736.. _tbl-pennames:
737
738    +------------+---------+------------+--------+
739    +============+=========+============+========+
740    | faint      | 0       | thicker    | 1.5p   |
741    +------------+---------+------------+--------+
742    | default    | 0.25p   | thickest   | 2p     |
743    +------------+---------+------------+--------+
744    | thinnest   | 0.25p   | fat        | 3p     |
745    +------------+---------+------------+--------+
746    | thinner    | 0.50p   | fatter     | 6p     |
747    +------------+---------+------------+--------+
748    | thin       | 0.75p   | fattest    | 10p    |
749    +------------+---------+------------+--------+
750    | thick      | 1.0p    | wide       | 18p    |
751    +------------+---------+------------+--------+
752
753.. _color_attrib:
754
755    The *color* can be specified in five different ways:
756
757    #. Gray. Specify a *gray* shade in the range 0–255 (linearly going
758       from black [0] to white [255]).
759
760    #. RGB. Specify *r*/*g*/*b*, each ranging from 0–255. Here 0/0/0 is
761       black, 255/255/255 is white, 255/0/0 is red, etc. Alternatively,
762       you can give RGB in hexadecimal using the *#rrggbb* format.
763
764    #. HSV. Specify *hue*-*saturation*-*value*, with the former in the
765       0–360 degree range while the latter two take on the range 0–1 [17]_.
766
767    #. CMYK. Specify *cyan*/*magenta*/*yellow*/*black*, each ranging
768       from 0–100%.
769
770    #. Name. Specify one of 663 valid color names. See :doc:`/gmtcolors` for
771       a list of all valid names. A very small yet versatile
772       subset consists of the 29 choices *white*, *black*, and
773       [light\|\ dark]{*red, orange, yellow, green, cyan, blue,
774       magenta, gray\|\ grey, brown*\ }. The color names are
775       case-insensitive, so mixed upper and lower case can be used (like
776       *DarkGreen*).
777
778    The *style* attribute controls the appearance of the line. Giving "dotted" or "."
779    yields a dotted line, whereas a dashed pen is requested with "dashed" or "-".
780    Also combinations of dots and dashes, like ".-" for a dot-dashed
781    line, are allowed. To override a default style and secure a solid line you can
782    specify "solid" for style.  The lengths of dots and dashes are scaled
783    relative to the pen width (dots has a length that equals the pen
784    width while dashes are 8 times as long; gaps between segments are 4
785    times the pen width). For more detailed attributes including exact
786    dimensions you may specify *string*\ [:*offset*], where *string* is a
787    series of numbers separated by underscores. These numbers represent
788    a pattern by indicating the length of line segments and the gap
789    between segments. The optional *offset* phase-shifts the pattern from the
790    beginning the line [0]. For example, if you want a yellow line of width
791    0.1 cm that alternates between long dashes (4 points), an 8 point
792    gap, then a 5 point dash, then another 8 point gap, with pattern
793    offset by 2 points from the origin, specify
794    **-W**\ 0.1c,yellow,4_8_5_8:2p. Just as with pen width, the
795    default style units are points, but can also be explicitly specified
796    in cm, inch, or points (see *width* discussion above).
797
798Table :ref:`penex <tbl-penex>` contains additional examples of pen specifications
799suitable for, say, :doc:`/plot`.
800
801.. _tbl-penex:
802
803+-------------------------------+-----------------------------------------------------+
804+===============================+=====================================================+
805| **-W**\ 0.5p                  | 0.5 point wide line of default color and style      |
806+-------------------------------+-----------------------------------------------------+
807| **-W**\ green                 | Green line with default width and style             |
808+-------------------------------+-----------------------------------------------------+
809| **-W**\ thin,red,-            | Dashed, thin red line                               |
810+-------------------------------+-----------------------------------------------------+
811| **-W**\ fat,.                 | Fat dotted line with default color                  |
812+-------------------------------+-----------------------------------------------------+
813| **-W**\ 0.1c,120-1-1          | Green (in h-s-v) pen, 1 mm thick                    |
814+-------------------------------+-----------------------------------------------------+
815| **-W**\ faint,100/0/0/0,..-   | Very thin, cyan (in c/m/y/k), dot-dot-dashed line   |
816+-------------------------------+-----------------------------------------------------+
817
818In addition to these pen settings there are several
819PostScript settings that can affect the appearance of lines. These are
820controlled via the GMT defaults settings :term:`PS_LINE_CAP`,
821:term:`PS_LINE_JOIN`, and :term:`PS_MITER_LIMIT`. They determine how a line
822segment ending is rendered, be it at the termination of a solid line or
823at the end of all dashed line segments making up a line, and how a
824straight lines of finite thickness should behave when joined at a common
825point, as shown in Figures :ref:`Cap <Cap_settings>` and :ref:`Miter <Miter_settings>`.
826
827.. _Cap_settings:
828
829.. figure:: /_images/GMT_cap.*
830   :width: 400 px
831   :align: center
832
833   Line appearance can be varied by using :term:`PS_LINE_CAP`, choosing from **SQUARE** [Default],
834   **ROUND**, or **BUTT**.  The circles and thin lines indicate the coordinates.  All lines
835   where plotted with the same width and dash-spacing (-W10p,20_20:0).
836
837.. toggle::
838
839   Here is the source script for the figure above:
840
841   .. literalinclude:: /_verbatim/GMT_cap.txt
842
843.. _Miter_settings:
844
845.. figure:: /_images/GMT_joint.*
846   :width: 550 px
847   :align: center
848
849   Given lines have finite thickness, there are three types of joints where line-segments
850   meet that can be adjusted with :term:`PS_LINE_JOIN`.  There is **BEVEL**, **ROUND**, and
851   **MITER**.  The last setting also depends on :term:`PS_MITER_LIMIT` which sets a limit on
852   the angle at the mitered joint below which we apply a bevel.
853
854.. toggle::
855
856   Here is the source script for the figure above:
857
858   .. literalinclude:: /_verbatim/GMT_joint.txt
859
860By default, line segments have rectangular ends, but this can
861change to give rounded ends. When :term:`PS_LINE_CAP` is set to round the
862a segment length of zero will appear as a circle. This can be used to
863created circular dotted lines, and by manipulating the phase shift in
864the *style* attribute and plotting the same line twice one can even
865alternate the color of adjacent items.
866Figure :ref:`Line appearance <Line_appearance>` shows various lines made in this
867fashion by adjusting the joint and cap settings as well as plotting lines twice with
868different phase *offset* and color. See the :doc:`/gmt.conf` man page for more information.
869
870.. _Line_appearance:
871
872.. figure:: /_images/GMT_linecap.*
873   :width: 500 px
874   :align: center
875
876   Line appearance can be varied by using :term:`PS_LINE_CAP`
877
878.. toggle::
879
880   Here is the source script for the figure above:
881
882   .. literalinclude:: /_verbatim/GMT_linecap.txt
883
884Experience has shown that the rendering of lines that are short relative to the pen thickness
885can sometimes appear wrong or downright ugly.  This is a feature of PostScript interpreters, such as
886Ghostscript.  By default, lines are rendered using a fast algorithm which is susceptible to
887errors for thick lines.  The solution is to select a more accurate algorithm to render the lines
888exactly as intended.  This can be accomplished by using the GMT Defaults :term:`PS_LINE_CAP`
889and :term:`PS_LINE_JOIN` by setting both to *round*.  Figure :ref:`Line appearance <Line_badrender>`
890displays the difference in results.
891
892.. _Line_badrender:
893
894.. figure:: /_images/GMT_fatline.*
895   :width: 500 px
896   :align: center
897
898   Very thick line appearance using the default (left) and round line cap and join (right).  The
899   red line (1p width) illustrates the extent of the input coordinates.
900
901.. toggle::
902
903   Here is the source script for the figure above:
904
905   .. literalinclude:: /_verbatim/GMT_fatline.txt
906
907Specifying line attributes
908--------------------------
909
910A line is drawn with the texture provided by the chosen pen (`Specifying pen attributes`_).
911However, depending on the module, a line also may have other attributes that can be changed in some modules.
912Given as modifiers to a pen specification, one or more modifiers may be appended to a pen
913specification. The line attribute modifiers are:
914
915
916* **+o**\ *offset*
917    Lines are normally drawn from the beginning to the end point. You can modify this behavior
918    by requesting a gap between these terminal points and the start and end of the
919    visible line.  Do this by specifying the desired offset between the terminal point and the
920    start of the visible line.  Unless you are giving distances in Cartesian data units,
921    please append the distance unit, **u**.  Depending on your desired effect, you can append
922    plot distance units (i.e., **c**\ m, **i**\ nch, **p**\ oint; Section `Dimension units`_)) or map distance units,
923    such as **k**\ m, **d**\ egrees, and many other standard distance units listed in
924    Section `GMT units`_.  If only one offset is given then it applies equally to both ends of
925    the line.  Give two slash-separated distances to indicate different offsets at the
926    beginning and end of the line (and use 0 to indicate no offset at one end).
927
928.. _Line_offset:
929
930.. figure:: /_images/GMT_lineoffset.*
931   :width: 500 px
932   :align: center
933
934   The thin red line shows an original line segment, whereas the 2-point thick pen illustrates the effect
935   of plotting the same line while requesting offsets of 1 cm at the beginning and 500 km
936   at the end, via **-W**\ 2p\ **+o**\ 1c/500k.
937
938.. toggle::
939
940   Here is the source script for the figure above:
941
942   .. literalinclude:: /_verbatim/GMT_lineoffset.txt
943
944* **+s**
945    Normally, all PostScript line drawing is implemented as a linear spline, i.e., we simply
946    draw straight line-segments between the map-projected data points.  Use this modifier to render the
947    line using Bezier splines for a smoother curve. **Note**: The spline is fit to the projected
948    2-D coordinates, not the raw user coordinates (i.e., it is not a spherical surface spline).
949
950.. _Line_bezier:
951
952.. figure:: /_images/GMT_bezier.*
953   :width: 500 px
954   :align: center
955
956   (left) Normal plotting of line given input points (red circles) via **-W**\ 2p. (right) Letting
957   the projected points be interpolated by a Bezier cubic spline via **-W**\ 2p\ **+s**.
958
959.. toggle::
960
961   Here is the source script for the figure above:
962
963   .. literalinclude:: /_verbatim/GMT_bezier.txt
964
965* **+v**\ [**b**\|\ **e**]\ *vspecs*
966    By default, lines are normally drawn from start to end.  Using the **+v** modifier you can
967    place arrow-heads pointing outward at one (or both) ends of the line.  Use **+v** if you
968    want the same vector attributes for both ends, or use **+vb** and **+ve** to specify a vector
969    only at the beginning or end of the line, respectively.  Finally, these two modifiers may both be given
970    to specify different attributes for the two vectors.  The vector specification is very rich
971    and you may place other symbols, such as circle, square, or a terminal cross-line, in lieu of the
972    vector head (see :doc:`/plot` for more details).
973
974.. _Line_vector:
975
976.. figure:: /_images/GMT_linearrow.*
977   :width: 500 px
978   :align: center
979
980   Same line as above but now we have requested a blue vector head at the end of the line and a
981   red circle at the beginning of the line with **-W**\ 2p\ **+o**\ 1c/500k\ **+vb**\ 0.2i\ **+g**\ red\ **+p**\ faint\ **+b**\ c\ **+ve**\ 0.3i\ **+g**\ blue.
982   Note that we also prescribed the line offsets in addition to the symbol endings.
983
984.. toggle::
985
986   Here is the source script for the figure above:
987
988   .. literalinclude:: /_verbatim/GMT_linearrow.txt
989
990.. _-Gfill_attrib:
991
992Specifying area fill attributes
993-------------------------------
994
995Many plotting programs will allow the user to draw filled polygons or
996symbols. The fill specification may take two forms (note: not all modules
997use **-G** for this task and some have several options specifying different fills):
998
999**-G**\ *fill*
1000    In the first case we may specify a *gray* shade (0–255), RGB color
1001    (*r*/*g*/*b* all in the 0–255 range or in hexadecimal *#rrggbb*),
1002    HSV color (*hue*-*saturation*-*value* in the 0–360, 0–1, 0–1 range),
1003    CMYK color (*cyan*/*magenta*/*yellow*/*black*, each ranging from
1004    0–100%), or a valid color *name*; in that respect it is similar to
1005    specifying the pen color settings (see pen color discussion under
1006    Section `Specifying pen attributes`_).
1007
1008**-GP**\|\ **p**\ *pattern*\ [**+b**\ *color*][**+f**\ *color*][**+r**\ *dpi*]
1009    The second form allows us to use a predefined bit-image pattern.
1010    *pattern* can either be a number in the range 1–90 or the name of a
1011    1-, 8-, or 24-bit image raster file. The former will result in one of
1012    the 90 predefined 64 x 64 bit-patterns provided with GMT and
1013    reproduced in Chapter :doc:`predefined-patterns`.
1014    The latter allows the user to create
1015    customized, repeating images using image raster files.
1016    The optional **+r**\ *dpi* modifier sets the resolution of this image on the page;
1017    the area fill is thus made up of a series of these "tiles".  The
1018    default resolution is 1200.  By specifying upper case **-GP**
1019    instead of **-Gp** the image will be bit-reversed, i.e., white and
1020    black areas will be interchanged (only applies to 1-bit images or
1021    predefined bit-image patterns). For these patterns and other 1-bit
1022    images one may specify alternative background and foreground colors
1023    (by appending **+b**\ *color* and/or **+f**\ *color*) that will replace
1024    the default white and black pixels, respectively. Excluding *color* from
1025    a fore- or background specification yields a *transparent* image where
1026    only the back- *or* foreground pixels will be painted.
1027
1028Due to PostScript implementation limitations the raster images used
1029with **-G** must be less than 146 x 146 pixels in size; for larger
1030images see :doc:`/image`. The format of Sun raster files [18]_ is
1031outlined in Chapter :doc:`file-formats`. However, if you built GMT
1032with GDAL then other image formats can be used as well. Note that under
1033PostScript Level 1 the patterns are filled by using the polygon as a
1034*clip path*. Complex clip paths may require more memory than the
1035PostScript interpreter has been assigned. There is therefore the
1036possibility that some PostScript interpreters (especially those
1037supplied with older laserwriters) will run out of memory and abort.
1038Should that occur we recommend that you use a regular gray-shade fill
1039instead of the patterns. Installing more memory in your printer *may or
1040may not* solve the problem!
1041
1042Table :ref:`fillex <tbl-fillex>` contains a few examples of fill specifications.
1043
1044.. _tbl-fillex:
1045
1046+-------------------------------------------------+-----------------------------------------------------+
1047+=================================================+=====================================================+
1048| **-G**\ 128                                     | Solid gray                                          |
1049+-------------------------------------------------+-----------------------------------------------------+
1050| **-G**\ 127/255/0                               | Chartreuse, R/G/B-style                             |
1051+-------------------------------------------------+-----------------------------------------------------+
1052| **-G**\ #00ff00                                 | Green, hexadecimal RGB code                         |
1053+-------------------------------------------------+-----------------------------------------------------+
1054| **-G**\ 25-0.86-0.82                            | Chocolate, h-s-v-style                              |
1055+-------------------------------------------------+-----------------------------------------------------+
1056| **-G**\ DarkOliveGreen1                         | One of the named colors                             |
1057+-------------------------------------------------+-----------------------------------------------------+
1058| **-Gp**\ 7\ **+r**\ 300                         | Simple diagonal hachure pattern in b/w at 300 dpi   |
1059+-------------------------------------------------+-----------------------------------------------------+
1060| **-Gp**\ 7\ **+b**\ red\ **+r**\ 300            | Same, but with red lines on white                   |
1061+-------------------------------------------------+-----------------------------------------------------+
1062| **-Gp**\ 7\ **+b**\ red\ **+f**\ -\ **+r**\ 300 | Now the gaps between red lines are transparent      |
1063+-------------------------------------------------+-----------------------------------------------------+
1064| **-Gp**\ marble.ras\ **+r**\ 100                | Using user image of marble as the fill at 100 dpi   |
1065+-------------------------------------------------+-----------------------------------------------------+
1066
1067Specifying Fonts
1068----------------
1069
1070The fonts used by GMT are typically set indirectly via the
1071GMT defaults parameters. However, some programs, like
1072:doc:`/text` may wish to have this
1073information passed directly. A font is specified by a comma-delimited
1074attribute list of *size*, *fonttype* and *fill*, each of which is
1075optional. The *size* is the font size (usually in points) but **c**,
1076**i** or **p** can be added to indicate a specific unit. The *fonttype*
1077is the name (case sensitive!) of the font or its equivalent numerical ID
1078(e.g., Helvetica-Bold or 1). The *fill* specifies the gray shade, color or
1079pattern of the text (see section `Specifying area fill attributes`_ above).
1080Optionally, you may append **=**\ *pen* to the *fill* value in order to draw a text
1081outline. If you want to avoid that the outline partially obscures the text,
1082append **=~**\ *pen* instead; in that case only half the linewidth is plotted
1083on the outside of the font only.  If an outline is requested, you may optionally
1084skip the text *fill* by setting it to **-**, in which case the full pen width
1085is always used. If any of the font attributes is omitted their default or
1086previous setting will be retained. See Chapter :doc:`postscript-fonts`
1087for a list of all fonts recognized by GMT.
1088
1089Stroke, Fill and Font Transparency
1090----------------------------------
1091
1092The PostScript language has no built-in mechanism for transparency.
1093However, PostScript extensions make it possible to request
1094transparency, and tools that can render such extensions will produce
1095transparency effects. We specify transparency in percent: 0 is opaque
1096[Default] while 100 is fully transparent (i.e., the feature will be invisible). As
1097noted in section :ref:`option_-t`, we can control transparency on a
1098layer-by-layer basis using the **-t** option. However, we may also set
1099transparency as an attribute of stroke or fill (including for fonts)
1100settings. Here, transparency is requested by appending @\ *transparency*
1101to colors or pattern fills. The transparency *mode* can be changed by
1102using the GMT default parameter :term:`PS_TRANSPARENCY`; the default is
1103Normal but you can choose among Color, ColorBurn, ColorDodge, Darken,
1104Difference, Exclusion, HardLight, Hue, Lighten, Luminosity, Multiply,
1105Normal, Overlay, Saturation, SoftLight, and Screen. For more
1106information, see for instance (search online for) the Adobe pdfmark
1107Reference Manual. Most printers and many PostScript viewers can
1108neither print nor show transparency. They will simply ignore your
1109attempt to create transparency and will plot any material as opaque.
1110Ghostscript and its derivatives such as GMT's
1111:doc:`/psconvert` support transparency (if
1112compiled with the correct build option). **Note**: If you use **Acrobat
1113Distiller** to create a PDF file you must first change some settings to
1114make transparency effective: change the parameter /AllowTransparency to
1115true in your \*.joboptions file.
1116
1117Placement of text
1118-----------------
1119
1120Many text labels placed on maps are part of the standard basemap
1121machinery (e.g., annotations, axis labels, plot titles) and GMT
1122automatically takes care of where these are placed and how they
1123are justified.  However, when you wish to add extra text to a plot
1124in locations of your choice you will need to understand how we
1125reference text to locations on the map.  Figure :ref:`Text justification <Text_justify>`
1126discusses the various ways to do this.
1127
1128.. _Text_justify:
1129
1130.. figure:: /_images/GMT_pstext_justify.*
1131   :width: 400 px
1132   :align: center
1133
1134   Text strings are placed on maps by associating an *anchor* point on
1135   the string with a *reference* point on the map.  Nine anchor points
1136   relative to any text string may be specified by combining any of
1137   three letter codes for horizontal (**L**\ eft, **C**\ enter, **R**\ ight)
1138   and vertical (**T**\ op, **M**\ iddle, **B**\ ottom) alignments.
1139
1140.. toggle::
1141
1142   Here is the source script for the figure above:
1143
1144   .. literalinclude:: /_verbatim/GMT_pstext_justify.txt
1145
1146Notice how the anchor points refers to the text baseline and do not change
1147for text whose letters extend below the baseline.
1148
1149The concept of anchor points extends to entire text paragraphs that you
1150may want to typeset with :doc:`/text`.
1151
1152A related point involves the
1153footprint of the text and any background panel on the map.  We determine
1154the bounding box for any text string, but very often we wish to extend this
1155box outwards to allow for some *clearance* between the text and the space
1156surrounding it.  Programs that allows for such clearance will let you
1157specify offsets *dx* and *dy* that is used to enlarge the bounding box,
1158as illustrated in Figure :ref:`Text clearance <Text_clearance>`.
1159
1160.. _Text_clearance:
1161
1162.. figure:: /_images/GMT_pstext_clearance.*
1163   :width: 300 px
1164   :align: center
1165
1166   The bounding box of any text string can be enlarged by specifying the
1167   adjustments *dx* and *dy* in the horizontal and vertical dimension.  The shape of the
1168   bounding box can be modified as well, including rounded or convex
1169   rectangles.  Here we have chosen a rounded rectangle, requiring the
1170   additional specification of a corner radius, *r*.
1171
1172.. toggle::
1173
1174   Here is the source script for the figure above:
1175
1176   .. literalinclude:: /_verbatim/GMT_pstext_clearance.txt
1177
1178.. _CPT_section:
1179
1180Color palette tables
1181--------------------
1182
1183Several programs need to relate user data to colors, shades, or even patterns.
1184For instance, programs that read 2-D gridded data sets and
1185create colored images or shaded reliefs  need to be told what colors to
1186use and over what *z*-range each color applies. Other programs may need
1187to associate a user value with a color to be applied to a symbol, line,
1188or polygon.  This is the purpose of the color palette table (CPT).  For
1189most applications, you will simply create a CPT using the tool
1190:doc:`/makecpt` which will take an existing *dynamic* master
1191color table and stretch it to fit your chosen data range, or use
1192:doc:`/grd2cpt` to build a CPT based on
1193the data distribution in one or more given grid files. However, in rare
1194situations you may need to make a CPT by hand or using text tools
1195like **awk** or **perl**. Finally, if you have your own preferred color
1196table you can convert it into a dynamic CPT and place it in your GMT
1197user directory and it will be found and behave like other GMT master CPTs.
1198
1199Color palette tables (CPT) comes in two flavors: (1) Those designed to
1200work with categorical data (e.g., data where interpolation of values is
1201undefined) and (2) those designed for regular, continuously-varying
1202data. In both cases the *fill* information follows the format given in
1203Section `Specifying area fill attributes`_. The z-values in CPTs can
1204be scaled by using the **+u**\|\ **U**\ *unit* mechanism.  Append these
1205modifiers to your CPT names when used in GMT commands.  The **+u**\ *unit*
1206modifier will scale z *from unit to* meters, while **+U**\ *unit* does
1207the inverse (scale z *from meters to unit*).
1208
1209**Note**: Users are allowed to name their CPT files anything they want, but
1210we recommend the use of the file extension ".cpt".  This allows us to prevent
1211any confusion when parsing filenames that may have sequences that otherwise
1212might look like a file *modifier* (e.g., data.my+u5.cpt). Since valid modifiers
1213are *appended* to a file name, finding such an extension simplifies parsing.
1214
1215Since GMT supports several coordinate systems for color specification,
1216many master (or user) CPTs will contain the special comment
1217
1218| ``# COLOR_MODEL = model``
1219
1220where *model* specifies how the color-values in the CPT should be interpreted.
1221By default we assume colors are given as red/green/blue triplets (each in the
12220-255 range) separated by
1223slashes (model = *rgb*), but alternative representations are the HSV system
1224of specifying hue-saturation-value triplets (with hue in 0-360 range and
1225saturation and value ranging from 0-1) separated by hyphens (model = *hsv*),
1226or the CMYK system of specifying cyan/magenta/yellow/black quadruples in percent,
1227separated by slashes (model = *cmyk*).
1228
1229Categorical CPTs
1230~~~~~~~~~~~~~~~~
1231
1232Categorical data are information on which normal numerical operations
1233are not defined. As an example, consider various land classifications
1234(desert, forest, glacier, etc.) and it is clear that even if we assigned
1235a numerical value to these categories (e.g., desert = 1, forest = 2,
1236etc) it would be meaningless to compute average values (what would 1.5
1237mean?). For such data a special format of the CPTs are provided.
1238Here, each category is assigned a unique key, a color or pattern, and an
1239optional label (usually the category name) marked by a leading
1240semi-colon. Keys (if numerical) must be monotonically increasing but do
1241not need to be consecutive. The format is
1242
1243+-----------------+--------+--------------+
1244| key\ :sub:`1`   | *Fill* | [;\ *label*] |
1245+-----------------+--------+--------------+
1246| ...             |        |              |
1247+-----------------+--------+--------------+
1248| key\ :sub:`n`   | *Fill* | [;\ *label*] |
1249+-----------------+--------+--------------+
1250
1251For usage with points, lines, and polygons, the keys may be text (single words),
1252and then GMT will use strings to find the corresponding *Fill* value. Strings
1253may be supplied as trailing text in data files (for points) or via the **-Z**\ *category*
1254option in multiple segment headers (or set via **-a**\ *Z*\ =\ *aspatialname*).
1255If any of your keys are called B, F, or N you must escape them with a leading backslash
1256to avoid confusion with the flags for background, foreground and NaN colors.
1257The *Fill* information follows the format given in Section `Specifying area fill attributes`_.
1258For categorical data, background color or foreground color do not apply. The not-a-number (NaN)
1259color (for *key*-values not found or blank) is defined in the :doc:`/gmt.conf` file, but it can be
1260overridden by the statement
1261
1262+-----+---------------------+
1263| N   | Fill\ :sub:`nan`    |
1264+-----+---------------------+
1265
1266While you can make such categorical CPTs by hand, both :doc:`/makecpt` and :doc:`/grd2cpt` have options to
1267simplify adding string keys and labels from comma-separated arguments.
1268
1269Regular CPTs
1270~~~~~~~~~~~~
1271
1272Suitable for continuous data types and allowing for color
1273interpolations, the format of the regular CPTs is:
1274
1275+---------------+-------------------+---------------+-------------------+----------+------------------------------+
1276| z\ :sub:`0`   | Color\ :sub:`min` | z\ :sub:`1`   | Color\ :sub:`max` | [**A**]  | [;\ *label*]                 |
1277+---------------+-------------------+---------------+-------------------+----------+------------------------------+
1278| ...                                                                                                             |
1279+---------------+-------------------+---------------+-------------------+----------+------------------------------+
1280| z\ :sub:`n-2` | Color\ :sub:`min` | z\ :sub:`n-1` | Color\ :sub:`max` | [**A**]  | [;\ *labell*\ [;\ *labelu*]] |
1281+---------------+-------------------+---------------+-------------------+----------+------------------------------+
1282
1283
1284Thus, for each "*z*-slice", defined as the interval between two
1285boundaries (e.g., :math:`z_0` to :math:`z_1`), the color can be
1286constant (by letting Color\ :math:`_{max}` = Color\ :math:`_{min}` or -)
1287or a continuous, linear function of *z*. If patterns are used then the
1288second (max) pattern must be set to -. The optional flag **A** is used
1289to indicate annotation of the color scale when plotted using
1290:doc:`/colorbar`. The optional flag **A** may
1291be **L**, **U**, or **B** to select annotation of the lower, upper, or
1292both limits of the particular *z*-slice, respectively. However,
1293the standard **-B** option can be used by
1294:doc:`/colorbar` to affect annotation and
1295ticking of color scales. Just as other GMT programs, the *stride* can
1296be omitted to determine the annotation and tick interval automatically
1297(e.g., **-Baf**). The optional semicolon followed by a text label will
1298make :doc:`/colorbar`, when used with the
1299**-L** option, place the supplied label instead of formatted *z*-values.
1300**Note**: If the last slice should have both lower and upper
1301custom labels then you must supply *two* semicolon-separated labels and set the
1302annotation code to **B**.
1303
1304
1305The background color (for *z*-values < :math:`z_0`), foreground color (for *z*-values >
1306:math:`z_{n-1}`), and not-a-number (NaN) color (for *z*-values =
1307NaN) are all defined in the :doc:`/gmt.conf` file, but can be overridden by the
1308statements
1309
1310+-----+---------------------+
1311| B   | Fill\ :sub:`back`   |
1312+-----+---------------------+
1313| F   | Fill\ :sub:`fore`   |
1314+-----+---------------------+
1315| N   | Fill\ :sub:`nan`    |
1316+-----+---------------------+
1317
1318which can be inserted into the beginning or end of the CPT. If you
1319prefer the HSV system, set the :doc:`/gmt.conf` parameter accordingly and replace red,
1320green, blue with hue, saturation, value. Color palette tables that
1321contain gray-shades only may replace the *r/g/b* triplets with a single
1322gray-shade in the 0–255 range. For CMYK, give *c/m/y/k* values in the
13230–100 range.
1324
1325A few programs (i.e., those that plot polygons such as
1326:doc:`/grdview`, :doc:`/colorbar`,
1327:doc:`/plot` and
1328:doc:`/plot3d`) can accept pattern fills instead
1329of gray-shades. You must specify the pattern as in Section `Specifying area fill attributes`_
1330(no leading **-G** of course), and only the first pattern (for low
1331*z*) is used (we cannot interpolate between patterns). Finally,
1332some programs let you skip features whose *z*-slice in the CPT
1333file has gray-shades set to -. As an example, consider
1334
1335+-----+----------+------+-----------+
1336| 30  | p16+r200 | 80   | \-        |
1337+-----+----------+------+-----------+
1338| 80  | \-       | 100  | \-        |
1339+-----+----------+------+-----------+
1340| 100 | 200/0/0  | 200  | 255/255/0 |
1341+-----+----------+------+-----------+
1342| 200 | yellow   | 300  | green     |
1343+-----+----------+------+-----------+
1344
1345where slice 30 < z < 80 is painted with pattern # 16 at 200 dpi,
1346slice 80 < z < 100 is skipped, slice 100 < z < 200 is
1347painted in a range of dark red to yellow, whereas the slice
1348200 < z < 300 will linearly yield colors from yellow to green,
1349depending on the actual value of *z*.
1350
1351Some programs like :doc:`/grdimage` and
1352:doc:`/grdview` apply artificial illumination
1353to achieve shaded relief maps. This is typically done by finding the
1354directional gradient in the direction of the artificial light source and
1355scaling the gradients to have approximately a normal distribution on the
1356interval [-1,+1]. These intensities are used to add "white" or "black"
1357to the color as defined by the *z*-values and the CPT. An intensity
1358of zero leaves the color unchanged. Higher values will brighten the
1359color, lower values will darken it, all without changing the original
1360hue of the color (see Chapter :doc:`colorspace` for more details). The
1361illumination is decoupled from the data grid file in that a separate
1362grid file holding intensities in the [-1,+1] range must be provided.
1363Such intensity files can be derived from the data grid using
1364:doc:`/grdgradient` and modified with
1365:doc:`/grdhisteq`, but could equally well be
1366a separate data set. E.g., some side-scan sonar systems collect both
1367bathymetry and backscatter intensities, and one may want to use the
1368latter information to specify the illumination of the colors defined by
1369the former. Similarly, one could portray magnetic anomalies superimposed
1370on topography by using the former for colors and the latter for shading.
1371
1372Master (dynamic) CPTs
1373~~~~~~~~~~~~~~~~~~~~~
1374
1375The CPTs distributed with GMT are *dynamic*.  This means they have several
1376special properties that modify the behavior of programs that use them.
1377Dynamic CPTs comes in a few different flavors: Some CPTs were designed
1378to behave differently across a *hinge* value (e.g., a CPT designed specifically
1379for topographic relief may include a discontinuity in color across the
1380coastline at *z = 0*), and when users select these CPTs they will be stretched
1381to fit the user's desired data range separately for each side of this *hard* hinge.
1382Basically, a *hard* hinge CPT is the juxtaposition of two different CPTs joined
1383at the hinge and these sections are stretched independently. Such CPT files
1384are identified as such via the special comment
1385
1386| ``# HARD_HINGE``
1387
1388and all hard hinges occur at data value *z = 0* (but you can change this value by
1389adding **+h**\ *value* to the name of the CPT).
1390Other CPTs may instead have a *soft* hinge which indicates a natural hinge or transition
1391point in the CPT itself, unrelated to any natural data set *per se*. These CPTs
1392are flagged by the special comment
1393
1394| ``# SOFT_HINGE``
1395
1396CPTs with soft hinges behave as regular (non-hinge) CPTs *unless* the user activates then by
1397appending **+h**\ [*hinge*] to the CPT name.  This modifier will convert the soft
1398hinge into a hard hinge at the user-specified data value *hinge* [which defaults to 0].
1399Note that if your specified data range *excludes* an activated soft or hard hinge then we
1400only perform color sampling from the *half* of the CPT that pertains to the data range.
1401All dynamic CPTs will need to be stretched to the user's preferred range, and there
1402are two modes of such scaling: Some CPTs designed for a specific application
1403(again, the topographic relief is a good example) have a *default range*
1404specified in the master table via the special comment
1405
1406
1407| ``# RANGE = <zmin/zmax>``
1408
1409and when used by applications the CPT may be automatically stretched to reflect
1410this natural range.  In contrast, dynamic CPTs *without* a natural range are instead
1411stretched to fit the range of the data in question (e.g., a grid's range).
1412Exceptions to these rules are implemented in the two *CPT-producing* modules
1413:doc:`/makecpt` and :doc:`/grd2cpt`, both of which can read dynamic CPTs
1414and produce *static* CPTs satisfying a user's specific range needs.  These
1415tools can also read static CPTs for which a new range must be specified (or computed
1416from data), reversing the order of colors, and even isolating a section
1417of an incoming CPT.  Here, :doc:`/makecpt` can be told the data range or compute
1418it from data tables while :doc:`/grd2cpt` can derive the range from one or more grids.
1419
1420.. figure:: /_images/GMT_hinge.*
1421   :width: 500 px
1422   :align: center
1423
1424   The top color bar is a dynamic master CPT (here, globe) with a hard hinge at sea level and
1425   a natural range from -10,000 to +10,000 meters. However, our data range
1426   is asymmetrical, going from -8,000 meter depths up to +3,000 meter elevations.
1427   Because of the hinge, the two sides of the CPT will be stretched separately
1428   to honor the desired range while utilizing the full color range.
1429
1430.. toggle::
1431
1432   Here is the source script for the figure above:
1433
1434   .. literalinclude:: /_verbatim/GMT_hinge.txt
1435
1436All CPT master tables can be found in Chapter :ref:`Of Colors and Color Legends`
1437where those with hard or soft hinges are identified by triangles at their hinges.
1438
1439CPTs from color lists
1440~~~~~~~~~~~~~~~~~~~~~
1441
1442GMT can build color tables "on the fly" from a comma-separated list of colors
1443and a range of *z*-values to go with them.  As illustrated below, there are
1444four different ways to create such CPTs. In this example, we will operate with
1445a list of three colors: red,yellow and purple, given to modules with the option **-C**\ red,yellow,purple,
1446and utilize a fixed data range of *z = 0-6*.
1447Four different CPTs result because we either select a *continuous* or *discrete table*, and because the *z*-intervals are
1448either *equidistant* or *arbitrary*.  The top continuous color table with equidistant spacing (a) is selected
1449with the range **-T**\ 0/6, meaning the colors will continuously change from red (at *z = 0*) via
1450yellow (at *z = 3*) to purple (at *z = 6*). Next, a discrete table with the same range (b)
1451is obtained with **-T**\ 0/6/2, yielding colors that are either constant red (*z = 0-2*), yellow (*z = 2-4*)
1452or purple (*z = 4-6*). The next discrete table (c) illustrates how to specify arbitrary
1453node points in the CPT by providing a comma-separated list of values (**-T**\ 0,4,5.5,6). Now, the constant
1454color intervals have unequal ranges, illustrated by red (*z = 0-4*), yellow (*z = 4-5.5*) and purple (*z = 5.5-6*).  Finally, we
1455create a continuous color table (d) with arbitrary nodes by giving **-T**\ 0,2,6 and adding **-Z**;
1456the latter option forces a continuous CPT pinned to a given list of node values.  Now, the colors
1457continuously change from red (at *z = 0*) via yellow (at *z = 2*) to purple (at *z = 6*).
1458Modules that obtain the *z*-range indirectly (e.g., :doc:`/grdimage`) may use the exact data range
1459to set the quivalent of a **-T**\ *min/max* option.  You may append **+i**\ *dz* to the
1460color list to have the *min* and *max* values rounded down and up to nearest multiple of *dz*, respectively.
1461
1462.. figure:: /_images/GMT_colorlist.*
1463   :width: 500 px
1464   :align: center
1465
1466   Lists of colors (here red,yellow,purple) can be turned into discrete or continuous CPT tables on the fly.
1467
1468.. toggle::
1469
1470   Here is the source script for the figure above:
1471
1472   .. literalinclude:: /_verbatim/GMT_colorlist.txt
1473
1474Cyclic (wrapped) CPTs
1475~~~~~~~~~~~~~~~~~~~~~
1476
1477Any color table you produce can be turned into a cyclic or *wrapped* color table.
1478This is performed by adding the **-Ww** option when running :doc:`/makecpt` or
1479:doc:`/grd2cpt`.  This option simply adds the special comment
1480
1481| ``# CYCLIC``
1482
1483to the color table and then GMT knows that when looking up a color from a *z*
1484value it will remove an integer multiple of the *z*-range represented by the
1485color table so that we are always inside the range of the color table.  This
1486means that the fore- and back-ground colors can never be activated.  Wrapped
1487color tables are useful for highlighting small changes.
1488
1489.. figure:: /_images/GMT_cyclic.*
1490   :width: 500 px
1491   :align: center
1492
1493   Cyclic color bars are indicated by a cycle symbol on the left side of the bar.
1494
1495.. toggle::
1496
1497   Here is the source script for the figure above:
1498
1499   .. literalinclude:: /_verbatim/GMT_cyclic.txt
1500
1501.. _manipulating_CPTs:
1502
1503Manipulating CPTs
1504~~~~~~~~~~~~~~~~~
1505
1506There are many ways to turn a master CPT into a custom CPT that works for your
1507particular data range.  The tools :doc:`/makecpt` and :doc:`/grd2cpt` allow
1508several types of transformations to take place:
1509
1510    #. You can reverse the *z*-direction of the CPT using option **-Iz**.
1511       This is useful when your data use a different convention for
1512       positive and negative (e.g., perhaps using positive depths instead of
1513       negative relief).
1514    #. You can invert the order of the colors in the CPT using option **-Ic**.
1515       This is different from the previous option in that only the colors
1516       are rearranged (it is also possible to issue **-Icz** to combine both effects.)
1517    #. You can select just a subset of a master CPT with **-G**, in effect creating
1518       a modified master CPT that can be scaled further.
1519    #. Finally, you can scale and translate the (modified) master CPT range to
1520       your actual data range or a sub-range thereof.
1521
1522The order of these transformations is important.  For instance, if **-Iz** is given
1523then all other *z*-values need to be referred to the new sign convention. For most
1524applications only the last transformation is needed.
1525
1526.. figure:: /_images/GMT_CPTscale.*
1527   :width: 500 px
1528   :align: center
1529
1530   Examples of two user CPTs for the range -0.5 to 3 created from the same master.  One (left) extracted a
1531   subset of the master before scaling while the other (right) used the entire range.
1532
1533.. toggle::
1534
1535   Here is the source script for the figure above:
1536
1537   .. literalinclude:: /_verbatim/GMT_CPTscale.txt
1538
1539Automatic CPTs
1540~~~~~~~~~~~~~~
1541
1542A few modules (:doc:`/grdimage`, :doc:`/grdview`) that expects a CPT option will
1543provide a default CPT if none is provided.  By default, the default CPT is the
1544*turbo* color table, but this is overridden if the user uses the @earth_relief
1545(we select *geo*) or @srtm_relief (we select *srtm*) data sets.  After selection,
1546these CPTs are read and scaled to match the range of the grid values. You may append
1547**+i**\ *dz* to the CPT to have the exact range rounded to nearest multiple of *dz*.
1548This is helpful if you plan to place a colorbar and prefer start and stop *z*-values
1549that are multiples of *dz*.
1550
1551The Drawing of Vectors
1552----------------------
1553
1554GMT supports plotting vectors in various forms. A vector is one of
1555many symbols that may be plotted by :doc:`/plot`
1556and :doc:`/plot3d`, is the main feature in
1557:doc:`/grdvector`, and is indirectly used by
1558other programs. All vectors plotted by GMT consist of two separate
1559parts: The vector line (controlled by the chosen pen attributes) and the
1560optional vector head(s) (controlled by the chosen fill). We distinguish
1561between three types of vectors:
1562
1563#. Cartesian vectors are plotted as straight lines. They can be
1564   specified by a start point and the direction and length (in map
1565   units) of the vector, or by its beginning and end point. They may
1566   also be specified giving the azimuth and length (in km) instead.
1567
1568#. Circular vectors are (as the name implies) drawn as circular arcs and
1569   can be used to indicate opening angles. It accepts an origin, a
1570   radius, and the beginning and end angles.
1571
1572#. Geo-vectors are drawn using great circle arcs. They are specified by
1573   a beginning point and the azimuth and length (in km) of the vector,
1574   or by its beginning and end point.
1575
1576.. figure:: /_images/GMT_arrows.*
1577   :width: 500 px
1578   :align: center
1579
1580   Examples of Cartesian (left), circular (middle), and geo-vectors (right)
1581   for different attribute specifications. Note that both full and half
1582   arrow-heads can be specified, as well as no head at all.
1583
1584.. toggle::
1585
1586   Here is the source script for the figure above:
1587
1588   .. literalinclude:: /_verbatim/GMT_arrows.txt
1589
1590There are numerous attributes you can modify, including how the vector
1591should be justified relative to the given point (beginning, center, or
1592end), where heads (if any) should be placed, if the head should just be
1593the left or right half, if the vector attributes should shrink for
1594vectors whose length are less than a given cutoff length, and the size
1595and shape of the head. These attributes are detailed further in the
1596relevant manual pages.
1597
1598.. figure:: /_images/GMT_arrows_types.*
1599   :width: 500 px
1600   :align: center
1601
1602   Examples of different vector heads and attributes.  The default is the standard
1603   triangular arrow head, which can be modified by adjusting the apex angle [30] or
1604   changing its shape via the :term:`MAP_VECTOR_SHAPE` setting.
1605   Other vector heads are the circle (**c**), the terminal line (**t**), the
1606   arrow fin (**i**) and the plain head (**A**) and tail (**I**); the last two
1607   are line-drawings only and cannot be filled.
1608
1609.. toggle::
1610
1611   Here is the source script for the figure above:
1612
1613   .. literalinclude:: /_verbatim/GMT_arrows_types.txt
1614
1615.. _Char-esc-seq:
1616
1617Character escape sequences
1618--------------------------
1619
1620For annotation labels or text strings plotted with
1621:doc:`/text`, GMT provides several escape
1622sequences that allow the user to temporarily switch to the symbol font,
1623turn on sub- or superscript, etc., within words. These conditions are
1624toggled on/off by the escape sequence @\ **x**, where **x** can be one
1625of several types. The escape sequences recognized in GMT are listed in
1626Table :ref:`escape <tbl-escape>`. Only one level of sub- or superscript is supported.
1627Note that under Windows the percent symbol indicates a batch variable,
1628hence you must use two percent-signs for each one required in the escape
1629sequence for font switching. In bash scripts the brackets have special meaning, hence you must add double quotes.
1630
1631.. _tbl-escape:
1632
1633+-------------------+----------------------------------------------------------------+
1634+===================+================================================================+
1635| @~                | Turns symbol font on or off                                    |
1636+-------------------+----------------------------------------------------------------+
1637| @+                | Turns superscript on or off                                    |
1638+-------------------+----------------------------------------------------------------+
1639| @-                | Turns subscript on or off                                      |
1640+-------------------+----------------------------------------------------------------+
1641| @#                | Turns small caps on or off                                     |
1642+-------------------+----------------------------------------------------------------+
1643| @\_               | Turns underline on or off                                      |
1644+-------------------+----------------------------------------------------------------+
1645| @%\ *fontno*\ %   | Switches to another font; @%% resets to previous font          |
1646+-------------------+----------------------------------------------------------------+
1647| @:\ *size*:       | Switches to another font size; @:: resets to previous size     |
1648+-------------------+----------------------------------------------------------------+
1649| @;\ *color*;      | Switches to another font color; @;; resets to previous color   |
1650+-------------------+----------------------------------------------------------------+
1651| @!                | Creates one composite character of the next two characters     |
1652+-------------------+----------------------------------------------------------------+
1653| @.                | Prints the degree symbol                                       |
1654+-------------------+----------------------------------------------------------------+
1655| @@                | Prints the @ sign itself                                       |
1656+-------------------+----------------------------------------------------------------+
1657
1658Shorthand notation for a few special European characters has also been added (for others
1659you must use the full octal code):
1660
1661
1662.. _tbl-shorthand:
1663
1664+----------+------------+----------+------------+
1665| *Code*   | *Effect*   | *Code*   | *Effect*   |
1666+==========+============+==========+============+
1667| @E       | Æ          | @e       | æ          |
1668+----------+------------+----------+------------+
1669| @O       | Ø          | @o       | ø          |
1670+----------+------------+----------+------------+
1671| @A       | Å          | @a       | å          |
1672+----------+------------+----------+------------+
1673| @C       | Ç          | @c       | ç          |
1674+----------+------------+----------+------------+
1675| @N       | Ñ          | @n       | ñ          |
1676+----------+------------+----------+------------+
1677| @U       | Ü          | @u       | ü          |
1678+----------+------------+----------+------------+
1679| @s       | ß          | @i       | í          |
1680+----------+------------+----------+------------+
1681
1682However, if your input text contains UTF-8 code characters (e.g., ü, Î)
1683and you select the ISOLatin1+ character encoding then GMT will substitute
1684the correct PostScript octal codes for you automatically.
1685
1686PostScript fonts used in GMT may be re-encoded to include several
1687accented characters used in many European languages. To access these,
1688you must specify the full octal code \\xxx allowed for
1689your choice of character encodings determined by the
1690:term:`PS_CHAR_ENCODING` setting described in the
1691:doc:`/gmt.conf` man page. Only the special
1692characters belonging to a particular encoding will be available. Many
1693characters not directly available by using single octal codes may be
1694constructed with the composite character mechanism @!.
1695
1696Some examples of escape sequences and embedded octal codes in
1697GMT strings using the Standard+ encoding:
1698
1699| ``2@~p@~r@+2@+h@-0@- E\363tv\363s`` = 2\ :math:`\pi r^2h_0` Eötvös
1700| ``10@+-3 @Angstr@om`` = 10\ :math:`^{-3}` Ångstrøm
1701| ``Stresses are @~s@~@+*@+@-xx@- MPa`` = Stresses are :math:`\sigma^{*}_{xx}` MPa
1702| ``Se@nor Gar@con`` = Señor Garçon
1703| ``M@!\305anoa stra@se`` = Manoa straße
1704| ``A@#cceleration@# (ms@+-2@+)`` = ACCELERATION (ms\ :math:`^{-2}`)
1705
1706The option in :doc:`/text` to draw a
1707rectangle surrounding the text will not work for strings with escape
1708sequences. A chart of characters and their octal codes is given in
1709Chapter :doc:`octal-codes`.
1710
1711.. _GMT_Embellishments:
1712
1713Plot embellishments
1714-------------------
1715
1716Apart from visualizing your data sets, GMT maps can also be embellished in several ways.
1717The 9 embellishments currently available are
1718
1719*  **Map scale** showing the true scale at some location(s) on the map.
1720
1721*  **Directional rose** showing true north and other cardinal directions.
1722
1723*  **Magnetic rose** showing magnetic north and declination deviations.
1724
1725*  **Color bar** relating the colors of your image to the data values.
1726
1727*  **Map legend** showing the meaning of the symbols on your map.
1728
1729*  **Image overlay** of raster images or EPS figures (e.g., institutional logos, photos, etc.).
1730
1731*  **GMT logo** overlay.
1732
1733*  **Map inset** showing perhaps the location of your detailed area in a regional or global context.
1734
1735*  **Vertical scale** showing the vertical scale of anomalies on a map.
1736
1737Each of these features share a common system for specifying the location on the plot where the
1738feature will be placed.  They also share a common way for specifying the placement of a rectangular
1739panel behind the feature (to provide a uniform background, for instance).  Thus, before we discuss
1740the different features in more detail we will first review the "reference point/anchor point"
1741system used by GMT to specify such locations in relation to the underlying map, and then discuss
1742the background panel attribute settings.
1743
1744.. _Reference_Points:
1745
1746Reference and anchor point specification
1747~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1748
1749.. figure:: /_images/GMT_anchor.*
1750   :width: 500 px
1751   :align: center
1752
1753   The placement of a map feature (here represented by a green rectangle) in relation
1754   to the underlying map.  The nine named *reference* points (blue circles) on the map perimeter (and center)
1755   can be used to specify a location.  Using the same system of nine points on the map feature
1756   (cyan circles) we select one of these as our *anchor* point (here TL, indicated by the orange square).
1757   The anchor point can optionally be shifted away from the reference point by an amount *dx/dy* in the direction
1758   implied by the anchor point (in this case to the top and left), yielding the adjusted
1759   anchor point (red square).
1760   The feature is then placed such that its adjusted anchor point matches the reference point.
1761
1762.. toggle::
1763
1764   Here is the source script for the figure above:
1765
1766   .. literalinclude:: /_verbatim/GMT_anchor.txt
1767
1768Placing a feature on the map means selecting a *reference* point somewhere on the map, an
1769*anchor* point somewhere on the feature, and then positioning the feature so that the two points overlap.
1770It may be helpful to consider the analog of a boat dropping an anchor: The boat navigates to the
1771reference point and then, depending on where on the boat the anchor is located, moves so that the
1772anchor connection point overlies the reference point, then drops the anchor.
1773There are four different ways to specify the reference point on a map, allowing for complete freedom
1774to select any location inside or outside the map.  The reference point syntax is [**g**\|\ **j**\|\ **J**\|\ **n**\|\ **x**]\ *refpoint*;
1775the five codes **g**\|\ **j**\|\ **J**\|\ **n**\|\ **x** refer to the five ways:
1776
1777.. _Reference_Points_g:
1778
1779#. [**g**] Specify *refpoint* using *data* coordinates, e.g., the longitude and latitude of the reference point.
1780   This mechanism is useful when you want to tie the location of the feature to an actual point
1781   best described by data coordinates.  An example of such a reference point might
1782   be **g**\ 135W/20N.
1783
1784.. _Reference_Points_j:
1785
1786#. [**j**] Specify *refpoint* using one of the nine *justification codes*, equivalent to the justification
1787   codes for placing text strings in :doc:`/text`.  This mechanism is illustrated in the figure above and
1788   is the preferred mechanism when you just want to place the feature **inside** the basemap at
1789   one of the corners or centered at one of the sides (or even smack in the middle).  Justification codes
1790   are a combination of a horizontal (**L**, **C**, **R**) and a vertical (**T**, **M**, **B**) code.
1791   An example of such a reference point might be **jTL**\ . When used, the anchor point on the map feature
1792   will default to the same justification, i.e., **TL** in this example.
1793
1794#. [**J**] This is the same as **j** except it implies that the default anchor point is the mirror opposite of the
1795   justification code. Thus, when using **JTL**\, the anchor point on the map feature will default to **BR**.
1796   This is practical for features that are drawn **outside** of the basemap (like color bars often are).
1797
1798.. _Reference_Points_x:
1799
1800#. [**x**] Specify *refpoint* using *plot* coordinates, i.e., the distances in inches, centimeters, or
1801   points from the lower left plot origin.  This mechanism is preferred when you wish to lay out
1802   map features using familiar measurements of distance from origins. An example of such a reference
1803   point might be **x**\ 2.75i/2c.
1804
1805.. _Reference_Points_n:
1806
1807#. [**n**] Specify *refpoint* using *normalized* coordinates, i.e., fractional coordinates between 0
1808   and 1 in both the *x* and *y* directions.  This mechanism avoids units and is useful if you want to always
1809   place features at locations best referenced as fractions of the plot dimensions.
1810   An example of such a reference point might be **n**\ 0.2/0.1.
1811
1812If no code is specified we default to **x**.
1813
1814.. _Anchor_Point_j:
1815
1816With the reference point taken care of, it is time to select the anchor point.
1817While the reference point selection gives unlimited flexibility to pick
1818any point inside or outside the map region, the anchor point selection is limited to the nine justification points
1819discussed for the **j** reference point code above.  Add **+j**\ *anchor* to indicate which justification
1820point of the map feature should be co-registered with the chosen reference point.  If an anchor point is not
1821specified then it defaults to the justification point set for the reference point (if **j**\ *code* was
1822used to set it), or to the mirror opposite of the reference point (if **J**\ *code* was used); with all other
1823specifications of the reference point, the anchor point takes on the default value of **MC** (for map rose and
1824map scale) or **BL** (all other map features). Adding **+j**\ *anchor* overrules those defaults.
1825For instance, **+jTR**\  would select the top right point on the map feature as the anchor.
1826
1827.. _Anchor_Point_o:
1828
1829It is likely that you will wish to offset the anchor point away from
1830your selection by some arbitrary amount, particularly if the reference point is specified with **j**\|\ **J**\ *code*.
1831Do so with  **+o**\ *dx*\ [/*dy*], where *dy* equals *dx* if it is not provided.
1832These increments are added to the projected plot coordinates of the anchor point, with
1833positive values moving the reference point in the same direction as the 2-character code of the anchor point implies.
1834Finally, the adjusted anchor point is matched with the reference point.
1835
1836Take for example an anchor point on the top left of the map feature, either by using a reference point **jTL**\ , or **JBR**\ ,
1837or explicitly setting **+j**\ TL.
1838Then **+o**\ 2c/1c will move the anchor point 2 cm left and 1 cm above the top left corner of the map feature.
1839In other words, the top left corner of the map feature will end up 2 cm to the right and 1 cm below the selected reference point.
1840
1841Similarly, **+jBR** will align the bottom right corner of the map feature, and **+o**\ 2c/1c will offset it 2 cm to the left
1842and 1 cm up. When using middle (**M**) or center (**C**) justifications, to offset works the same way as bottom (**B**) or left (**L**),
1843respectively, i.e., moving the map feature up or to the right.
1844
1845.. _Background-panel:
1846
1847The background panel
1848~~~~~~~~~~~~~~~~~~~~
1849
1850For most maps you will wish to place a background panel of uniform color behind
1851any of the map features you plan to add.  Because the panel is linked to the map feature
1852you have selected, the parameters such as location and dimensions are handled automatically.
1853What remains is to specify the *attributes* of the panel.  Typically, panels settings are
1854given via a module's **-F** option by appending one or more modifiers.  Here is a list of
1855the attributes that are under your control:
1856
1857#. Color or pattern.  You specify the fill you want with **+g**\ *fill* [Default is no fill].
1858   For instance, paint the panel yellow with **+g**\ yellow.
1859
1860#. Panel frame pen.  Turn on the frame outline with **+p**, using the pen defined via
1861   :term:`MAP_FRAME_PEN`.  You may override this choice with **+p**\ *pen*
1862   [Default is no outline].  A very bold red outline might look like **+p**\ thick,red.
1863
1864#. Rounded versus straight rectangle.  By specifying a corner radius with **+r**\ *radius*
1865   you can round the corners [Default is no rounding]. Here is a 0.5-cm radius rounding:
1866   **+r**\ 0.5c.
1867
1868#. Inner frame.  A secondary, inner frame outline may be added as well with the modifier
1869   **+i**\ [[*gap*/]\ *pen*].  The default pen is given by :term:`MAP_DEFAULT_PEN`,
1870   with a default *gap* between the outer and inner frames of 2 points.  Add arguments to override
1871   these defaults, such as **+i**\ 0.1c/thin,dashed to get a thin, dashed inner frame offset by
1872   0.1 cm from the main (outer) frame.
1873
1874#. Panel clearance.  The panel's dimensions are automatically determined from knowledge of
1875   its contents.  However, it is sometimes required to add some extra clearance around most or
1876   all sides, and you can do so with **+c**\ [*clearance*], with a 4-point clearance being
1877   the default.  Add one (uniform), two (different horizontal and vertical clearances), or
1878   four (separate for sides west, east, south, and north) clearances, separated by slashes.  For instance, to add
1879   a 1 cm clearance in x and 5 points in y, use **+c**\ 1c/5p.
1880
1881#. Drop-down shadow.  Append **+s** to simulate a gray shadow cast toward the southeast.
1882   You may append [*dx*/*dy*/][*shade*] to change the shade color and the offset of the
1883   shade [Default is 4p/-4p/gray50].  If happy with the placement but desiring a dark blue
1884   shadow, add **+s**\ darkblue.
1885
1886.. figure:: /_images/GMT_panel.*
1887   :width: 400 px
1888   :align: center
1889
1890   A map panel is a rectangular background placed behind any of the map features.  It has
1891   several attributes that can be changed with panel option modifiers.  The light green rounded
1892   rectangle was specified with **-F+g**\ lightgreen\ **+r**, while the white panel on the
1893   lower right was set with **-F+p**\ 1p\ **+i+s+g**\ white\ **+c**\ 0.1i (we added a light
1894   dashed box to indicate the effect of the clearance setting).
1895
1896.. toggle::
1897
1898   Here is the source script for the figure above:
1899
1900   .. literalinclude:: /_verbatim/GMT_panel.txt
1901
1902.. _Placing-map-scales:
1903
1904Placing map scales
1905~~~~~~~~~~~~~~~~~~
1906
1907Traditionally, a map scale is added to maps for helping the reader understand the particular scale
1908used for this map, i.e., it portrays the relationship between actual distances on the Earth
1909(in km, miles, meters, etc.) and distances on the map (in cm, inches, points).  Depending on
1910the map projection the map scale will vary continuously but may be constant along a line of
1911latitude (e.g., Mercator projection).  Thus, in placing the map scale on the map there are
1912two locations involved: (1) The *reference* point where the map scale's *anchor* should be
1913pinned, and (2) the *projection* point where the scale is computed and thus where the map
1914scale is true.  Map scales can be plotted by :doc:`/basemap` or :doc:`/coast`, and in
1915addition to the the required *refpoint* and anchor arguments specifying where the scale should be placed there
1916are both required and optional modifiers.  These are given via these modules' **-L** option.
1917Here is a list of the attributes that is under your control:
1918
1919#. Scale bar length.  Required modifier is given with **+w**\ *length*, where
1920   *unit* is one of the recognized distance units.  An example might be **+w**\ 250n for
1921   a bar representing 250 nautical miles at the map scale origin.
1922
1923#. Map scale origin.  Required modifier given with **+c**\ [*slon*/]\ *slat*, where the longitude
1924   of the scale origin is optional for projections with constant scale along parallels.  For
1925   a Mercator projection it may look like **+c**\ 30N while an oblique projection may need **+c**\ 100W/23N,
1926   for instance.
1927
1928#. Fancy scale bar.  By default a plain-looking scale bar is plotted.  For a free upgrade to a fancier bar,
1929   append **+f**.  The fancier bar is, well, a bit fancier.
1930
1931#. Scale label. Turn on scale labels with **+l**.  By default, the scale label is initialized to
1932   equal the distance unit name.  Use the **+l**\ *label* argument to supply your own scale label,
1933   such as **+l**\ "Distances at Equator".
1934
1935#. Scale label alignment.  The default alignment is on top of the bar [**+at**], but you can change
1936   this by selecting another alignment by appending them to the **+a** modifier, including
1937   **b**\ ottom, **l**\ eft, or **r**\ ight.  Here, **+ab** would align on the bottom of the scale.
1938
1939#. Append distance unit.  For the fancy scale, adding **+u** will append the distance unit specified
1940   with **+w** to all distance annotations along the bar, while for the plain scale it will replace
1941   the default scale label with the unit abbreviation.
1942
1943.. figure:: /_images/GMT_mapscale.*
1944   :width: 500 px
1945   :align: center
1946
1947   Example of two map scales for a Mercator projection evaluated at 53 degrees north.
1948   The left-most scale was placed with **-Lj**\ *ML*\ **+c**\ 53\ **+w**\ 1000k\ **+f+l**\ "Scale at 53\\232N"
1949   while the scale on the right was placed with **-Lj**\ *BR*\ **+c**\ 53\ **+w**\ 1000k\ **+l+f**.
1950
1951.. toggle::
1952
1953   Here is the source script for the figure above:
1954
1955   .. literalinclude:: /_verbatim/GMT_mapscale.txt
1956
1957Note that for the purpose of anchor justification (**+j**) the footprint of the map scale is
1958considered the rectangle that contains the scale and all selected labels and annotations, i.e.,
1959the map scale's *bounding box*.
1960
1961.. _Placing-dir-map-roses:
1962
1963Placing directional map roses
1964~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1965
1966Map roses showing the cardinal directions of a map help the reader orient themselves, especially
1967for oblique projections where north-south is not vertically aligned.  However, these roses also
1968have ornamental value and can be used on any map projection.  As for map scales, a directional
1969map rose is added with :doc:`/basemap` or :doc:`/coast` and selected by the **-Td** option.
1970This option accepts the *reference* point where the map rose's *anchor* should be
1971pinned.  In addition to the required *refpoint* and *anchor* arguments (and their standard
1972modifiers discussed earlier) there is one required and two optional modifiers. The required
1973modifier sets the side:
1974
1975#. Size of map rose.  Use **+w**\ *size* to specify the full width and height of the rose.  A 3 cm
1976   rose would require **+w**\ 3c.
1977
1978The next two modifiers are optional:
1979
1980#. Cardinal points.  By default only the four cardinal points (W, E, S, N) are included in the rose.
1981   You can extend that with the **+f**\ *level* modifier, where *level* is 1 [Default], 2, or 3.  Selecting
1982   2 will include the two intermediate orientations NW-SE and NE-SW, while 3 adds the four additional
1983   orientations WNW-ESE, NNW-SSE, NNE-SSW, and ENE-WSW.
1984
1985#. Add labels.  Do so with **+l**,  which places the current one-letter codes for west, east, south,
1986   and north at the four cardinal points.  These letters depend on the setting of :term:`GMT_LANGUAGE`
1987   and for the default English we use W, E, S, N, respectively.  You can replace these labels with four custom
1988   labels via  **+l**\ *w,e,s,n*, i.e., four comma-separated labels in the specified order.  You can exclude any
1989   of the cardinal points from being labeled by giving no label in the corresponding order.  E.g., **+l**",,Down,Up"
1990   would write Down and Up at the south and north cardinal point, respectively.  Note that for the plain
1991   directional rose only the north annotation will be placed.
1992
1993.. figure:: /_images/GMT_dir_rose.*
1994   :width: 500 px
1995   :align: center
1996
1997   Plain and fancy directional map roses. (left) Bare-bones plain rose showing arrow towards north
1998   and a cross indicating the cardinal directions, specified by **-Tdg**\ 0/0\ **+w**\ 1i. (middle) Fancy rose
1999   obtained by adding **+f** and **+l**\ ,,,N to get the north label.  (right) Fancy directional rose
2000   at level 3 with labels by adding **+f**\ 3\ **+l**.
2001
2002.. toggle::
2003
2004   Here is the source script for the figure above:
2005
2006   .. literalinclude:: /_verbatim/GMT_dir_rose.txt
2007
2008.. _Placing-mag-map-roses:
2009
2010Placing magnetic map roses
2011~~~~~~~~~~~~~~~~~~~~~~~~~~
2012
2013Map roses showing the magnetic directions of a map are useful when magnetic data are presented,
2014or when declinations are significantly nonzero.  However, as for directional roses the magnetic rose
2015also has ornamental value.  The magnetic rose consists of two concentric angular scales: The first
2016(outer) ring shows directional angles while the second (inner) ring is optional and portrays the
2017magnetic directions, which differ for nonzero declination. As for style, the two-ring rose looks a
2018bit like a standard compass.  As for directional roses, a magnetic
2019map rose is added with :doc:`/basemap` or :doc:`/coast` and selected by the **-Tm** option.
2020As for other features, append the required *reference* point where the magnetic map rose's *anchor*
2021should be pinned.  There is one required and several optional modifiers.  First up is the size:
2022
2023#. Specify size of map rose.  Use **+w**\ *size* to specify the full width of the rose.  A 3 cm
2024   rose would imply **+w**\ 3c.
2025
2026The remaining modifiers are optional:
2027
2028#. Specify Declination.  To add the inner angular scale, append **d**\ *dec*\ [/\ *dlabel*], where
2029   *dec* is the declination value in decimal or ddd:mm:ss format, and *dlabel* is an optional string
2030   that replaces the default label (which is "d = *dec*", with d being a Greek delta and we format
2031   the specified declination).  Append **d**\ *dec*/- to indicate you do not want any declination label.
2032   As an example, consider **d**\ 11/"Honolulu declination".
2033
2034#. Draw the secondary (outer) ring outline.  Normally it is not drawn, but you can change that by appending
2035   **+p**\ *pen*.  For instance, adding **+p**\ thin will draw the ring with the selected thin pen.
2036
2037#. Add labels.  As for directional roses you do so with **+l**, which places the current one-letter codes for west, east, south,
2038   and north at the four cardinal points.  These letters depend on the setting of :term:`GMT_LANGUAGE`
2039   and for the default English we use W, E, S, N, respectively.  You can replace these labels with four custom
2040   labels via  **+l**\ *w,e,s,n*, i.e., four comma-separated labels in the specified order.  You can exclude any
2041   of the cardinal points from being labeled by giving no label in the corresponding order.  E.g., **+l**",,Down,Up"
2042   would write Down and Up at the south and north cardinal point, respectively.
2043
2044#. Draw the primary (inner) ring outline.  It is also not normally drawn; change that by appending
2045   **+i**\ *pen*.  For instance, adding **+i**\ thin,blue will draw the ring with the selected thin, blue pen.
2046
2047#. Set annotation, tick and grid intervals.  Each ring has a default annotation [30], tick [5], and grid [1]
2048   interval (although here "grid interval" is just a finer tick interval drawn at half tickmark length).
2049   Adjust these three intervals with **+t**\ *intervals*.  If you selected **+d** then you must supply
2050   two sets of such intervals (i.e., 6 comma-separated values), where the first (primary) set refers to
2051   the declination-adjusted ring and the second (secondary) set refers to the directional (outer) ring.
2052   If only three intervals are given then we assume you want the same intervals for both rings.  As an example,
2053   to annotate every 90 degrees and tick every 15 and 5 degrees, add **+t**\ 90/15/5.
2054
2055.. figure:: /_images/GMT_mag_rose.*
2056   :width: 600 px
2057   :align: center
2058
2059   Magnetic direction map rose. This symbol is quite complicated and has many items whose attributes are
2060   in part controlled by GMT defaults parameters and in part by the above modifiers.  The color-coded legend
2061   indicates which parameters controls the font, pen, or color of the correspond item of the rose.  This rose
2062   was specified by **-Tmg**\ -2/0.5\ **+w**\ 2.5i\ **+d**\ -14.5\ **+t**\ 45/10/5\ **+i**\ 0.25p,blue\ **+p**\ 0.25p,red\ **+l+j**\ CM.
2063   See :doc:`/gmt.conf` for more details on the default parameters.
2064
2065.. toggle::
2066
2067   Here is the source script for the figure above:
2068
2069   .. literalinclude:: /_verbatim/GMT_mag_rose.txt
2070
2071Placing color scale bars
2072~~~~~~~~~~~~~~~~~~~~~~~~
2073
2074Color scale bars are used in conjunction with color-coded surfaces, symbols, lines, or even text, to
2075relate the chosen color to a data value or category.  For instance, color images of topography
2076or other gridded data will need a mechanism for users to decode what the colors represent.  Typically, we do this
2077by adding a color scale bar on the outside (or inside) of the map boundaries.  The module
2078:doc:`/colorbar` places the color scale bar, with location and size determined by the **-D** attributes.
2079As for other map features we must specify the reference and anchor points and any adjustments to them, then
2080supply suitable required and optional modifiers:
2081
2082#. Give dimensions of color bar.  Use **+w**\ *length*/*width* to specify the full width and height of the bar.
2083   For instance, a 10 cm long bar of height 0.5 cm would imply **+w**\ 10c/0.5c.
2084
2085#. Set orientation of color bar.  By default, we place a vertically aligned bar.  Select a horizontal bar by
2086   adding **+h**.
2087
2088#. Specify color bar label alignment.  By default we place the chosen annotations, scale (i.e., x-axis) label
2089   and unit (i.e., y-axis) label on the opposite side of the color scale bar anchor point.  Change this
2090   with **+m** and append any combination of **a**, **l**, or **u** to flip the annotations or labels
2091   to the opposite side.  Append **c** to plot vertical labels as column text (this cannot be used with
2092   **+h**, obviously).
2093
2094#. Extend the color bar.  You can use the **+e** modifier to add sidebar triangles for displaying the
2095   current back- and foreground colors.  Append **b** (background) or **f** (foreground) to get the implied side
2096   only [Default is both].  Optionally, append triangle height [Default is half the bar *width*].
2097
2098#. Add missing data key.  Append **+n** to draw a rectangle with the current NaN color and label it NaN.
2099   Optionally, append a replacement *text*.  One example might be **+n**\ "No data".
2100
2101.. figure:: /_images/GMT_colorbar.*
2102   :width: 500 px
2103   :align: center
2104
2105   Color bar placed beneath a map (here truncated).  We extended the bar to show background and foreground
2106   colors, and used the frame-annotation machinery to add labels.  The bar was placed with
2107   **-D**\ *JBC*\ **+o**\ 0/0.35i\ **+w**\ 4.5i/0.1i\ **+h**.
2108
2109.. toggle::
2110
2111   Here is the source script for the figure above:
2112
2113   .. literalinclude:: /_verbatim/GMT_colorbar.txt
2114
2115Placing map legends
2116~~~~~~~~~~~~~~~~~~~
2117
2118Adding map legends is the standard way to communicate what various symbols placed on your map
2119represent.  For instance, you may use this mechanism to convey the information that circles are
2120earthquake locations, triangles are places where you ate Thai food, and dashed lines indicate
2121some sort of gang-land demarkation line that you should not cross without paying the locals due respect.
2122Map legends are placed by the module :doc:`/legend`, with location and size determined by the
2123various **-D** attributes. We must again specify the reference and anchor points and any adjustments to them
2124first, then supply suitable required and optional modifiers:
2125
2126#. Give legend dimensions.  You must specify the required legend width, while legend height is optional
2127   and if not given is computed based on the contents of the legend.  The syntax is therefore
2128   **+w**\ *width*\ [/*height*] in your desired plot units.  Thus, **+w**\ 12c sets the legend width
2129   as 12 cm but the height will become whatever is needed to contain the information.
2130
2131#. Set line-spacing.  You may optionally specify the line-spacing used for the setting of the legend.  The legend will
2132   typically consist of several lines that may or may not contain text, but the spacing between
2133   these lines are controlled by the chosen line-spacing factor times the current primary annotation
2134   font setting, i.e., :term:`FONT_ANNOT_PRIMARY`.  The default line spacing factor
2135   is 1.1; change this with **+l**\ *linefactor*.
2136
2137.. figure:: /_images/GMT_legend.*
2138   :width: 500 px
2139   :align: center
2140
2141   Example of a map legend placed with :doc:`/legend`.  Apart from the placement and dimensions discussed
2142   here, :doc:`/legend` reads macro commands that specifies each item of the legend, including colors,
2143   widths of columns, the number of columns, and presents a broad selection of items.  Here, we
2144   simply used **-Dx**\ 0/0\ **+w**\ 14c\ **+j**\ *BL*.
2145
2146.. toggle::
2147
2148   Here is the source script for the figure above:
2149
2150   .. literalinclude:: /_verbatim/GMT_legend.txt
2151
2152Placing raster and EPS images on maps
2153~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2154
2155When preparing posters for meetings one will often need to include the organization's logo,
2156which may be available to you as an Encapsulated PostScript File (EPS) or as a raster image,
2157such as PNG or JPG.  At other times, you may wish to place photos or other raster images on
2158your map.  The module :doc:`/image` can help with this, and like the other map feature
2159placements it requires a reference point and its optional adjustments via the **-D** option.
2160In addition, we require one (of two) modifiers to determine the image size.
2161
2162#. Specify image width.  This is a required modifier and is set via **+w**\ *width*\ [/*height*].
2163   If *height* is specified as 0 then we compute the height from *width* and the aspect
2164   ratio of the image, for instance **+w**\ 4c/0.  If *width* is negative the we use its absolute value as width
2165   but interpolate the image in PostScript to the device resolution.
2166
2167#. Specify image resolution.  For raster images (not EPS) you may instead specify the size of the
2168   plotted image by specifying its resolution in dots per inch, via **+r**\ *dpi*.  The
2169   actual size of the images is then controlled by its number of pixels times the *dpi*.
2170
2171#. Enable image replication.  For raster images (not EPS) you may optionally append **+n**\ *nx*\ [/*ny*]
2172   to indicate that you want the source image to be replicated that many times in the two
2173   directions, resulting in a tiling of the map using the selected image.  This may be useful
2174   in conjunction with an active clip path set by :doc:`/clip`.
2175
2176.. figure:: /_images/GMT_images.*
2177   :width: 500 px
2178   :align: center
2179
2180   Placement of EPS and raster images. (left) The US National Science Foundation (NSF) has
2181   generously funded the development of GMT and their JPG logo is reproduced here via
2182   **-Dj**\ *ML*\ **+w**\ 1.5i\ **+o**\ 0.1i. (right)
2183   The School of Ocean and Earth Science and Technology at the University of Hawaii at Manoa
2184   hosts the gmt server and its EPS logo is shown via **-Dj**\ *MR*\ **+o**\ 0.1i\ **+w**\ 2i.
2185
2186.. toggle::
2187
2188   Here is the source script for the figure above:
2189
2190   .. literalinclude:: /_verbatim/GMT_images.txt
2191
2192Placing a GMT logo on maps
2193~~~~~~~~~~~~~~~~~~~~~~~~~~
2194
2195It is possible to overlay the GMT logo on maps as well, using the module :doc:`/gmtlogo`.
2196Like other features it requires reference and anchor points and their optional adjustments via the **-D** option.
2197In addition, we require one modifier to set the logo's size.
2198
2199#. Specify logo width.  This is a required modifier and is set via **+w**\ *width*.
2200   The height is automatically set (it is half the width).  To place a 5 cm wide
2201   GMT logo, append **+w**\ 5c.
2202
2203.. figure:: /_images/GMT_coverlogo.*
2204   :width: 300 px
2205   :align: center
2206
2207   Placement of the GMT logo. The logo itself only has a size modifier but the :doc:`/gmtlogo`
2208   module allows additional attributes such as a background map panel.
2209
2210.. toggle::
2211
2212   Here is the source script for the figure above:
2213
2214   .. literalinclude:: /_verbatim/GMT_coverlogo.txt
2215
2216Placing map insets
2217~~~~~~~~~~~~~~~~~~
2218
2219Our penultimate map embellishment is the map inset.
2220A map inset may appear to be the easiest feature to add since it only consists of an empty map panel.
2221What you put in this panel is up to you (and we will show some examples).  However, unlike
2222the other map features there are two ways to specify the placement of the map inset.
2223The first is the standard way of specifying the reference and anchor points and the inset dimensions,
2224while the second specifies a *subregion* in the current plot that should be designated the
2225map inset area.  Depending on the map projection this may or may not be a rectangular area.
2226Map insets are produced by the module :doc:`/inset` and located via the **-D** option. Unless you
2227use the reference point approach you must first append *xmin*/*xmax*/*ymin*/*ymax*\ [**+r**][**+u**\ *unit*],
2228where the optional *unit* modifier **+u** indicates that the four coordinates to follow are projected
2229distances (e.g., km, miles).  If the unit modifier is missing then we assume the coordinates are
2230map coordinates (e.g., geographic *west*, *east*, *south*, and *north*).  For oblique
2231projections you may wish to specify the domain using the lower-left and upper-right coordinates
2232instead (similar to how the **-R** option works), by adding **+r**\ .  Some optional modifiers are available:
2233
2234#. Set inset size.  If you specified a reference point then you must also specify the inset dimensions with the
2235   **+w**\ *width*\ [/*height*], where *height* defaults to *width* if not given.
2236   Append the unit of the dimensions, which may be distance units such as km, feet, etc., and
2237   the map projection will be used to determine inset dimensions on the map.  For instance,
2238   **+w**\ 300k/200k is a 300x200 km region (which depends on the projection) while **+w**\ 5c
2239   is a 5cm square box.
2240
2241#. Save the location and dimensions.  For all but the simplest of map insets you will need to
2242   know the exact location of the resulting inset and its dimensions.  For instance, if you
2243   specified the inset using the **TR** anchor point and a width and height of 100 km you will need to
2244   know what this means in terms of positions on the map in plot units.  In terms of the modifiers
2245   this would be **jTR**\ **+w**\ 100k.  See the figure caption for an example.
2246
2247.. figure:: /_images/GMT_inset.*
2248   :width: 500 px
2249   :align: center
2250
2251   Demonstration of how a map inset may be used to place a global overview map as an inset in a
2252   regional map.  Main map shows the regional area of Australia.  We place an inset in the upper
2253   right area with **-Dj**\ TR\ **+w**\ 3.8c\ **+o**\ 0.4c/0.25c.
2254   See Example :ref:`example_44` for more details.
2255
2256.. toggle::
2257
2258   Here is the source script for the figure above:
2259
2260   .. literalinclude:: /_verbatim/GMT_inset.txt
2261
2262Placing a vertical scale on maps
2263~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2264
2265Our final embellishment is reserved for wiggles plotted along track with :doc:`/wiggle` and
2266is activated as an option within that module.
2267Like other features, it requires reference and anchor points and their optional adjustments via the **-D** option.
2268In addition, we offer a few modifier to set the scale bar's remaining attributes:
2269
2270#. Specify vertical scale bar length.  This is a required modifier and is set via **+l**\ *length*.
2271   The length is given in the data (*z*) units of your plot.  To indicate that your vertical scale bar
2272   should reflect 100 nTesla, append **+l**\ 100.  The actual dimension of the scale bar on your map
2273   depends on the data scale set in :doc:`/wiggle` via **-Z**.
2274
2275#. Place the label on the left side of the vertical scale bar.  This is an optional modifier and is set via **+m**.
2276   By default, the scale bar has open ``teeth`` pointing right and a label on that side. The **m** moves the
2277   label to the left and reverses the teeth direction as well.
2278
2279#. Add a unit to the vertical scale bar label.  This is an optional modifier and is set via **+u**\ *unit*.
2280   To append nT (nTesla) to the label you would specify **+u**\ nT.
2281
2282.. figure:: /_images/GMT_vertscale.*
2283   :width: 600 px
2284   :align: center
2285
2286   Placement of a vertical scale bar. As for other embellishments the :doc:`/wiggle`
2287   module allows additional attributes such as a background map panel.
2288
2289.. toggle::
2290
2291   Here is the source script for the figure above:
2292
2293   .. literalinclude:: /_verbatim/GMT_vertscale.txt
2294
2295.. _grid-file-format:
2296
2297Grid file format specifications
2298-------------------------------
2299
2300GMT has the ability to read and write grids using more than one grid file format
2301(see Table :ref:`grdformats <tbl-grdformats>` for supported format and their IDs).
2302For reading, GMT will automatically determine the format of grid files, while for
2303writing you will normally have to append *=ID* to the filename if you want GMT to
2304use a different format than the default. The automatic reading procedure follows an heuristic
2305where certain formats are tentatively decoded with GMT internal drivers and if they fail than
2306we resort to use the GDAL library to do the readings. This normally works pretty well but in case
2307of failure (e.g. a GMT driver failed to read binary file with a separate header that also could
2308have been stored in an ASCII file with embed header) the user should explicitly try to force a
2309reading via GDAL. That is, to append a *=gd* suffix to file name.
2310
2311By default, GMT will create new grid files using the **nf** format;
2312however, this behavior can be overridden by setting the
2313:term:`IO_GRIDFILE_FORMAT` defaults parameter to any of the other
2314recognized values (or by appending *=ID*).
2315
2316GMT can also read netCDF grid files produced by other software
2317packages, provided the grid files satisfy the COARDS and Hadley Centre
2318conventions for netCDF grids. Thus, products created under those
2319conventions (provided the grid is 2-, 3-, 4-, or 5-dimensional) can be
2320read directly by GMT and the netCDF grids written by GMT can be read
2321by other programs that conform to those conventions. Three such programs are
2322`ncview <https://cirrus.ucsd.edu/~pierce/software/ncview/index.html>`_, `Panoply
2323<http://www.giss.nasa.gov/tools/panoply/>`_, and `ncBrowse
2324<https://www.pmel.noaa.gov/epic/java/ncBrowse/>`_ ; others can be found on the
2325`netCDF website <http://www.unidata.ucar.edu/software/netcdf/software.html>`_.
2326Note that although many additional programs can read netCDF files, some are unable
2327to read netCDF 4 files (if data compression has been applied).
2328
2329In addition, users with some C-programming experience may add their own
2330read/write functions and link them with the GMT library to extend the
2331number of predefined formats. Technical information on this topic can be
2332found in the source file ``gmt_customio.c``. Users who are considering this
2333approach should contact the GMT team for guidance.
2334
2335.. _tbl-grdformats:
2336
2337+----------+---------------------------------------------------------------+
2338| **ID**   | **Explanation**                                               |
2339+==========+===============================================================+
2340|          | *GMT 4 netCDF standard formats*                               |
2341+----------+---------------------------------------------------------------+
2342| nb       | GMT netCDF format (8-bit integer, COARDS, CF-1.5)             |
2343+----------+---------------------------------------------------------------+
2344| ns       | GMT netCDF format (16-bit integer, COARDS, CF-1.5)            |
2345+----------+---------------------------------------------------------------+
2346| ni       | GMT netCDF format (32-bit integer, COARDS, CF-1.5)            |
2347+----------+---------------------------------------------------------------+
2348| nf       | GMT netCDF format (32-bit float, COARDS, CF-1.5)              |
2349+----------+---------------------------------------------------------------+
2350| nd       | GMT netCDF format (64-bit float, COARDS, CF-1.5)              |
2351+----------+---------------------------------------------------------------+
2352|          | *GMT 3 netCDF legacy formats*                                 |
2353+----------+---------------------------------------------------------------+
2354| cb       | GMT netCDF format (8-bit integer, depreciated)                |
2355+----------+---------------------------------------------------------------+
2356| cs       | GMT netCDF format (16-bit integer, depreciated)               |
2357+----------+---------------------------------------------------------------+
2358| ci       | GMT netCDF format (32-bit integer, depreciated)               |
2359+----------+---------------------------------------------------------------+
2360| cf       | GMT netCDF format (32-bit float, depreciated)                 |
2361+----------+---------------------------------------------------------------+
2362| cd       | GMT netCDF format (64-bit float, depreciated)                 |
2363+----------+---------------------------------------------------------------+
2364|          | *GMT native binary formats*                                   |
2365+----------+---------------------------------------------------------------+
2366| bm       | GMT native, C-binary format (bit-mask)                        |
2367+----------+---------------------------------------------------------------+
2368| bb       | GMT native, C-binary format (8-bit integer)                   |
2369+----------+---------------------------------------------------------------+
2370| bs       | GMT native, C-binary format (16-bit integer)                  |
2371+----------+---------------------------------------------------------------+
2372| bi       | GMT native, C-binary format (32-bit integer)                  |
2373+----------+---------------------------------------------------------------+
2374| bf       | GMT native, C-binary format (32-bit float)                    |
2375+----------+---------------------------------------------------------------+
2376| bd       | GMT native, C-binary format (64-bit float)                    |
2377+----------+---------------------------------------------------------------+
2378|          | *Miscellaneous grid formats*                                  |
2379+----------+---------------------------------------------------------------+
2380| rb       | SUN raster file format (8-bit standard)                       |
2381+----------+---------------------------------------------------------------+
2382| rf       | GEODAS grid format GRD98 (NCEI)                               |
2383+----------+---------------------------------------------------------------+
2384| sf       | Golden Software Surfer format 6 (32-bit float)                |
2385+----------+---------------------------------------------------------------+
2386| sd       | Golden Software Surfer format 7 (64-bit float)                |
2387+----------+---------------------------------------------------------------+
2388| af       | Atlantic Geoscience Center AGC (32-bit float)                 |
2389+----------+---------------------------------------------------------------+
2390| ei       | ESRI Arc/Info ASCII Grid Interchange format (ASCII integer)   |
2391+----------+---------------------------------------------------------------+
2392| ef       | ESRI Arc/Info ASCII Grid Interchange format (ASCII float)     |
2393+----------+---------------------------------------------------------------+
2394| gd       | Import/export via GDAL [19]_                                  |
2395+----------+---------------------------------------------------------------+
2396
2397Because some formats have limitations on the range of values they can
2398store it is sometimes necessary to provide more than simply the name of
2399the file and its ID on the command line. For instance, a native short
2400integer file may use a unique value to signify an empty node or NaN, and
2401the data may need translation and scaling prior to use. Therefore, all
2402GMT programs that read or write grid files will decode the given
2403filename as follows:
2404
2405name[=\ *ID*][**+d**\ *divisor*][**+n**\ *invalid*][**+o**\ *offset*][**+s**\ *scale*]
2406
2407where anything in brackets is optional. If you are reading a grid then
2408no *ID* is needed: just continue to pass the name of the grid file.
2409However, if you write another format than the default netCDF you must append
2410the =\ *ID* string, where *ID* is the format code listed above. In addition,
2411should you want to (1) multiply the data by a *scale* factor (or alternatively
2412divide the data by a *divisor*), and (2) add a constant offset you must append
2413the **+s**\ *scale* (or **+d**\ *divisor*) and **+o**\ *offset* modifiers.
2414Finally, if you need to indicate that a certain data value should be interpreted
2415as a NaN (not-a-number) you must append **+n**\ *invalid* modifier to file name.
2416For output, you may specify scale as *a* for auto-adjusting the scale and/or offset of
2417packed integer grids (=\ *ID*\ **+s**\ *a* is a shorthand for
2418=\ *ID*\ **+s**\ *a*\ **+o**\ *a*).
2419
2420**Note**: Users are allowed to name their grid files anything they want.  However,
2421if you tend to use what *could* look like modifier-sequences to GMT (e.g., using
2422filenames like data.grid+o4) you can prevent any confusion by using either the
2423GMT-recommended ".grd" or ".nc" as grid file extensions (e.g., data.my+o4.grd).
2424Since valid modifiers are *appended* to a file name, finding such an extension simplifies parsing.
2425
2426Note that the GMT netCDF and native binary grids store the grid scale and offset
2427in the file, hence if you specify these attributes when writing a file then upon reading the grid
2428these settings will automatically take effect.  You can override them by supplying different scales
2429and offsets, of course.  For the  grid formats that do not store these attributes
2430you will need to supply them both when reading and writing.
2431
2432Some of the grid formats allow writing to standard output and reading
2433from standard input which means you can connect GMT programs that
2434operate on grid files with pipes, thereby speeding up execution and
2435eliminating the need for large, intermediate grid files. You specify
2436standard input/output by leaving out the filename entirely. That means
2437the "filename" will begin with "=\ *ID*". Note that the netCDF format
2438does not allow piping.
2439
2440Everything looks clearer after a few examples:
2441
2442*  To write a native binary float grid file, specify the name as ``my_file.f4=bf`` .
2443
2444*  To read a native short integer grid file, multiply the data by 10 and
2445   then add 32000, but first let values that equal 32767 be set to NaN,
2446   use the filename ``my_file.i2=bs+s10+o32000+n32767``.
2447
2448*  To read a Golden Software "surfer" format 6 grid file, just pass the
2449   file name, e.g., ``my_surferfile.grd``.
2450
2451*  To read a 8-bit standard Sun raster file (with values in the 0–255
2452   range) and convert it to a 1 range, give the name as ``rasterfile+s7.84313725e-3+o-1``
2453   (i.e., 1/127.5).
2454
2455*  To write a native binary short integer grid file to standard output
2456   after subtracting 32000 and dividing its values by 10, give filename
2457   as ``=bs+s0.1+o-3200``.
2458
2459*  To write an 8-bit integer netCDF grid file with an auto-adjusted
2460   offset, give filename as ``=nb+oa``.
2461
2462*  To read a short integer *.bil* grid file stored in binary and and force
2463   the reading via GDAL, add suffix *=gd* as in ``n45_e008_1arc_v3.bil=gd``
2464
2465*  To write a lossless, deflate compressed, and tiled GeoTIFF grid (or image) use,
2466   ``output.tif=gd:GTiff+cTILED=YES+cCOMPRESS=DEFLATE+cPREDICTOR=3``
2467   See also :ref:`Writing grids and images <Write-grids-images>` as well as available options
2468   for each output format from the GDAL driver documentation,
2469   `for example <https://gdal.org/drivers/raster/gtiff.html>`_
2470
2471Programs that both read and/or write more than one grid file may specify
2472different formats and/or scaling for the files involved. The only
2473restriction with the embedded grid specification mechanism is that no
2474grid files may actually use the "=" character as part of their name
2475(presumably, a small sacrifice).
2476
2477One can also define special file suffixes to imply a specific file
2478format; this approach represents a more intuitive and user-friendly way
2479to specify the various file formats. The user may create a file called
2480``gmt.io`` in the current directory or home directory, or in the directory
2481``~/.gmt`` and define any number of custom formats. The following is an example of
2482a ``gmt.io`` file:
2483
2484+---------------------------------------------------------------------------+
2485| # GMT i/o shorthand file                                                  |
2486|                                                                           |
2487| # It can have any number of comment lines like this one anywhere          |
2488| # suffix format_id scale offset NaN Comments                              |
2489+-------+-----+-----+---+-------+-------------------------------------------+
2490| grd   | nf  | \-  | \-| \-    | Default format                            |
2491+-------+-----+-----+---+-------+-------------------------------------------+
2492| b     | bf  | \-  | \-| \-    | Native binary floats                      |
2493+-------+-----+-----+---+-------+-------------------------------------------+
2494| i2    | bs  | \-  | \-| 32767 | 2-byte integers with NaN value            |
2495+-------+-----+-----+---+-------+-------------------------------------------+
2496| ras   | rb  | \-  | \-| \-    | Sun raster files                          |
2497+-------+-----+-----+---+-------+-------------------------------------------+
2498| byte  | bb  | \-  | \-| 255   | Native binary 1-byte grids                |
2499+-------+-----+-----+---+-------+-------------------------------------------+
2500| bit   | bm  | \-  | \-| \-    | Native binary 0 or 1 grids                |
2501+-------+-----+-----+---+-------+-------------------------------------------+
2502| mask  | bm  | \-  | \-| 0     | Native binary 1 or NaN masks              |
2503+-------+-----+-----+---+-------+-------------------------------------------+
2504| faa   | bs  | 0.1 | \-| 32767 | Native binary gravity in 0.1 mGal         |
2505+-------+-----+-----+---+-------+-------------------------------------------+
2506| ns    | ns  | a   | a | \-    | 16-bit integer netCDF grid with           |
2507|       |     |     |   |       | auto-scale and auto-offset                |
2508+-------+-----+-----+---+-------+-------------------------------------------+
2509
2510These suffices can be anything that makes sense to the user. To activate
2511this mechanism, set parameter :term:`IO_GRIDFILE_SHORTHAND` to TRUE in
2512your :doc:`/gmt.conf` file. Then, using the filename ``stuff.i2`` is equivalent to saying ``stuff.i2=bs+n32767``, and the
2513filename ``wet.mask`` means wet.mask=bm+n0. For a file intended for masking, i.e.,
2514the nodes are either 1 or NaN, the bit or mask format file may be as
2515small as 1/32 the size of the corresponding grid float format file.
2516
2517Modifiers for changing units of grid coordinates
2518------------------------------------------------
2519
2520A few GMT tools require that the two horizontal dimensions be
2521specified in meters. One example is
2522:doc:`/grdfft` which must compute the 2-D
2523Fourier transform of a grid and evaluate wave numbers in the proper units
2524(1/meter). There are two situations where the user may need to change
2525the coordinates of the grid passed to such programs:
2526
2527-  You have a geographic grid (i.e., in longitude and latitude). Simply
2528   supply the **-fg** option and your grid coordinates will
2529   automatically be converted to meters via a "Flat Earth" approximation
2530   on the currently selected ellipsoid (**Note**: This is only possible in
2531   those few programs that require this capability. In general, **-fg**
2532   is used to specify table coordinates).
2533
2534-  You have a Cartesian grid but the units are not meters (e.g., they
2535   may perhaps be in km or miles). In this case you may append the file
2536   modifier **+u**\ *unit*, where *unit* is one of non-angular units listed
2537   in Table :ref:`distunits <tbl-distunits>`. For example, reading in the grid (which has
2538   distance units of km) and converting distances to meters is done by
2539   specifying the filename as *filename*\ **+u**\ k. On output, any derived grids will revert
2540   to their original units *unless* you specify another unit modifier to
2541   the output grid. This may be used, for instance, to save the original
2542   grid with distances in meters using some other unit.
2543
2544For convenience, we also support the inverse translation, i.e.,
2545**+U**\ *unit*. This modifier can be used to convert your grid
2546coordinates *from* meters *to* the specified unit. Example :ref:`example_28` shows a
2547case where this is being used to change an UTM grid in meters to km.
2548These modifiers are only allowed when map projections are not selected
2549(or are Cartesian).
2550
2551.. _modifiers-for-CF:
2552
2553Modifiers for COARDS-compliant netCDF files
2554-------------------------------------------
2555
2556When the netCDF grid file contains more than one 2-dimensional variable,
2557GMT programs will load the first such variable in the file and ignore
2558all others. Alternatively, the user can select the required variable by
2559adding the suffix "?\ *varname*" to the grid file name. For example, to
2560get information on the variable "slp" in file , use:
2561
2562   ::
2563
2564    gmt grdinfo "file.nc?slp"
2565
2566Since COARDS-compliant netCDF files are the default, the additional
2567suffix "=nf" can be omitted.
2568
2569If there are no 2-dimensional variables and no specific variable was
2570selected, we default to the first higher-dimensional matrix and select
2571the first layer.
2572
2573In case the named grid is 3-dimensional, GMT will load the first
2574(bottom) layer. If another layer is required, either add "[*index*]"
2575or "(*level*)", where *index* is the index of the third (depth) variable
2576(starting at 0 for the first layer) and *level* is the numerical value
2577of the third (depth) variable associated with the requested layer. To
2578indicate the second layer of the 3-D variable "slp" use as file name: ``file.nc?slp[1]``.
2579
2580When you supply the numerical value for the third variable using
2581"(*level*)", GMT will pick the layer closest to that value. No
2582interpolation is performed.
2583
2584Note that the question mark, brackets and parentheses have special
2585meanings on Unix-based platforms. Therefore, you will need to either
2586*escape* these characters, by placing a backslash in front of them, or
2587place the whole file name plus modifiers between single quotes or double
2588quotes.
2589
2590A similar approach is followed for loading 4-dimensional grids. Consider
2591a 4-dimensional grid with the following variables:
2592
2593   ::
2594
2595    lat(lat): 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
2596    lon(lon): 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
2597    depth(depth): 0, 10, 20, 30, 40, 50, 60, 70, 80, 90
2598    time(time): 0, 12, 24, 36, 48
2599    pressure(time,depth,lat,lon): (5000 values)
2600
2601To get information on the 10x10 grid of pressure at
2602depth 10 and at time 24, one would use:
2603
2604   ::
2605
2606    gmt grdinfo "file.nc?pressure[2,1]"
2607
2608or (only in case the coordinates increase linearly):
2609
2610   ::
2611
2612    gmt grdinfo "file.nc?pressure(24,10)"
2613
2614Programs that generally deal with columns of one-dimensional data, like
2615or can use multi-dimensional netCDF files in a very similar way. If a
2616variable in a netCDF file is one-dimensional, there is nothing more
2617needed than name the variables on the command line. For example:
2618
2619   ::
2620
2621    gmt plot "file.nc?lon/lat" ...
2622    gmt convert "file.nc?time/lat/lon"
2623
2624If one or more of the selected variables are two-dimensional, and have
2625the same leading dimension as the other selected variables they will be
2626plotted in their entirety. For example, if a netCDF files contains 6
2627time steps recording temperature at 4 points, and the variable ``temp`` is a 6 by
26284 array, then the command ``gmt convert "file.nc?time/temp"`` can result in:
2629
2630   ::
2631
2632    2012-06-25T00:00:00 20.1 20.2 20.1 20.3
2633    2012-06-25T12:00:00 24.2 23.2 24.5 23.5
2634    2012-06-26T00:00:00 16.1 16.2 16.1 16.3
2635    2012-06-26T12:00:00 22.1 23.0 23.9 23.5
2636    2012-06-27T00:00:00 17.5 16.9 17.2 16.8
2637    2012-06-27T12:00:00 27.2 27.2 27.5 27.5
2638
2639If, for example, only the second temperature column is needed, use
2640``gmt convert "file.nc?time/temp[1]"`` (indices start counting at 0).
2641
2642The COARDS conventions set restrictions on the names that can be used
2643for the units of the variables and coordinates. For example, the units
2644of longitude and latitude are "degrees_east" and "degrees_north",
2645respectively. Here is an example of the header of a COARDS compliant
2646netCDF file (to be obtained using **ncdump**):
2647
2648   ::
2649
2650    netcdf M2_fes2004 {
2651    dimensions:
2652            lon = 2881 ;
2653            lat = 1441 ;
2654    variables:
2655            float lon(lon) ;
2656                    lon:long_name = "longitude" ;
2657                    lon:units = "degrees_east" ;
2658                    lon:actual_range = 0., 360. ;
2659            float lat(lat) ;
2660                    lat:long_name = "latitude" ;
2661                    lat:units = "degrees_north" ;
2662                    lat:actual_range = -90., 90. ;
2663            short amp(lat, lon) ;
2664                    amp:long_name = "amplitude" ;
2665                    amp:unit = "m" ;
2666                    amp:scale_factor = 0.0001 ;
2667                    amp:add_offset = 3. ;
2668                    amp:_FillValue = -32768s ;
2669            short pha(lat, lon) ;
2670                    pha:long_name = "phase" ;
2671                    pha:unit = "degrees" ;
2672                    pha:scale_factor = 0.01 ;
2673                    pha:_FillValue = -32768s ;
2674
2675This file contains two grids, which can be plotted separately using the
2676names ``M2_fes2004.nc?amp`` and ``M2_fes2004.nc?pha``. The attributes ``long_name`` and ``unit`` for each variable
2677are combined in GMT to a single unit string. For example, after
2678reading the grid ``y_unit`` equals ``latitude [degrees_north]``. The
2679same method can be used in reverse to set the proper variable names and
2680units when writing a grid. However, when the coordinates are set
2681properly as geographical or time axes, GMT will take care of this. The
2682user is, however, still responsible for setting the variable name and
2683unit of the z-coordinate. The default is simply "z".
2684
2685Modifiers to read and write grids and images via GDAL
2686-----------------------------------------------------
2687
2688If the support has been configured during installation, then GMT can
2689read and write a variety of grid and image formats via GDAL. This
2690extends the capability of GMT to handle data sets from a variety of
2691sources.
2692
2693Reading multi-band images
2694~~~~~~~~~~~~~~~~~~~~~~~~~
2695
2696:doc:`/grdimage` and :doc:`/image` both lets the user select
2697individual bands in a multi-band image file and treats the result as an
2698image (that is the values, in the 0–255 range, are treated as colors,
2699not data). To select individual bands you use the **+b**\ *band-number*
2700mechanism that must be appended to the image filename. Here,
2701*band-number* can be the number of one individual band (the counting
2702starts at zero), or it could be a comma-separated list of bands. For example
2703
2704   ::
2705
2706    gmt image jpeg_image_with_three_bands.jpg+b0 -jpg gray
2707
2708will plot only the first band (i.e., the red band) of the jpeg image as
2709a gray-scale image, and
2710
2711   ::
2712
2713    gmt image jpeg_image_with_three_bands.jpg+b2,1,0 -jpg bgr
2714
2715will plot the same image in color but where the RGB band order has been reversed.
2716
2717Instead of treating them as images, all other GMT programs that
2718process grids can read individual bands from an image but will consider
2719the values to be regular data. For example, let ``multiband`` be the name of a
2720multi-band file with a near infrared component in band 4 and red in band
27213. We will compute the NDVI (Normalized Difference Vegetation Index),
2722which is defined as NDVI = (NIR - R) / (NIR + R), as
2723
2724   ::
2725
2726    gmt grdmath multiband=gd+b3 multiband=gd+b2 SUB multiband=gd+b3 \
2727                multiband=gd+b2 ADD DIV = ndvi.nc
2728
2729The resulting grid ``ndvi.nc`` can then be plotted as usual.
2730
2731Reading more complex multi-band IMAGES or GRIDS
2732~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2733
2734It is also possible to access to sub-datasets in a multi-band grid. The
2735next example shows how we can extract the SST from the MODIS file ``A20030012003365.L3m_YR_NSST_9``
2736that is stored in the HDF "format". We need to run the GDAL program
2737**gdalinfo** on the file because we first
2738must extract the necessary metadata from the file:
2739
2740.. code-block:: none
2741
2742    gdalinfo A20030012003365.L3m_YR_NSST_9
2743    Driver: HDF4/Hierarchical Data Format Release 4
2744    Files: A20030012003365.L3m_YR_NSST_9
2745    Size is 512, 512
2746    Coordinate System is `'
2747    Metadata:
2748     Product Name=A20030012003365.L3m_YR_NSST_9
2749     Sensor Name=MODISA
2750     Sensor=
2751     Title=MODISA Level-3 Standard Mapped Image
2752    ...
2753     Scaling=linear
2754     Scaling Equation=(Slope*l3m_data) + Intercept = Parameter value
2755     Slope=0.000717185
2756     Intercept=-2
2757     Scaled Data Minimum=-2
2758     Scaled Data Maximum=45
2759     Data Minimum=-1.999999
2760     Data Maximum=34.76
2761    Subdatasets:
2762     SUBDATASET_1_NAME=HDF4_SDS:UNKNOWN:"A20030012003365.L3m_YR_NSST_9":0
2763     SUBDATASET_1_DESC=[2160x4320] l3m_data (16-bit unsigned integer)
2764     SUBDATASET_2_NAME=HDF4_SDS:UNKNOWN:"A20030012003365.L3m_YR_NSST_9":1
2765     SUBDATASET_2_DESC=[2160x4320] l3m_qual (8-bit unsigned integer)
2766
2767Now, to access this file with GMT we need to use the =gd mechanism and
2768append the name of the sub-dataset that we want to extract. Here, a
2769simple example using :doc:`/grdinfo` would be
2770
2771   ::
2772
2773    gmt grdinfo A20030012003365.L3m_YR_NSST_9=gd?HDF4_SDS:UNKNOWN:"A20030012003365.L3m_YR_NSST_9":0
2774
2775    HDF4_SDS:UNKNOWN:A20030012003365.L3m_YR_NSST_9:0: Title: Grid imported via GDAL
2776    HDF4_SDS:UNKNOWN:A20030012003365.L3m_YR_NSST_9:0: Command:
2777    HDF4_SDS:UNKNOWN:A20030012003365.L3m_YR_NSST_9:0: Remark:
2778    HDF4_SDS:UNKNOWN:A20030012003365.L3m_YR_NSST_9:0: Gridline node registration used
2779    HDF4_SDS:UNKNOWN:A20030012003365.L3m_YR_NSST_9:0: Grid file format: gd = Import through GDAL (convert to float)
2780    HDF4_SDS:UNKNOWN:A20030012003365.L3m_YR_NSST_9:0: x_min: 0.5 x_max: 4319.5 x_inc: 1 name: x nx: 4320
2781    HDF4_SDS:UNKNOWN:A20030012003365.L3m_YR_NSST_9:0: y_min: 0.5 y_max: 2159.5 y_inc: 1 name: y ny: 2160
2782    HDF4_SDS:UNKNOWN:A20030012003365.L3m_YR_NSST_9:0: z_min: 0 z_max: 65535 name: z
2783    HDF4_SDS:UNKNOWN:A20030012003365.L3m_YR_NSST_9:0: scale_factor: 1 add_offset: 0
2784
2785Be warned, however, that things are not yet completed because while the
2786data are scaled according to the equation printed above ("Scaling
2787Equation=(Slope\*l3m_data) + Intercept = Parameter value"), this
2788scaling is not applied by GDAL on reading so it cannot be done
2789automatically by GMT. One solution is to do the reading and scaling
2790via :doc:`/grdmath` first, i.e.,
2791
2792   ::
2793
2794    gmt grdmath A20030012003365.L3m_YR_NSST_9=gd?HDF4_SDS:UNKNOWN:"A20030012003365.L3m_YR_NSST_9":0 \
2795                0.000717185 MUL -2 ADD = sst.nc
2796
2797then plot the ``sst.nc`` directly.
2798
2799.. _Write-grids-images:
2800
2801Writing grids and images
2802~~~~~~~~~~~~~~~~~~~~~~~~
2803
2804Saving images in the common raster formats is possible but, for the time being, only from :doc:`/grdimage` and even
2805that is restricted to raster type information. That is, vector data (for instance, coast lines) or text will not
2806be saved. To save an image with :doc:`/grdimage` use the **-A**\ *outimg=driver* mechanism, where *driver*
2807is the driver code name used by GDAL (e.g. GTiff) (run `gdal_translate --formats` for the full list.)
2808
2809For all other programs that create grids, it is also possible to save them using GDAL. To do it one need to use
2810the =gd appended with the necessary information regarding the driver and the data type to use. Generically,
2811=\ **gd**\ [**+s**\ *scale*][**+o**\ *offset*][**+n**\ *nan*][:<*driver*\ >[/\ *dataType*][**+c**\ *options*]]
2812where *driver* is the same as explained above and *dataType* is a 2 or 3 chars code from:
2813u8\|u16\|i16\|u32\|i32\|float32, and where i\|u denotes signed\|unsigned. If not provided the default type
2814is float32. Both driver names and data types are case insensitive. The *options* is a list of one or more concatenated
2815number of GDAL *-co* options. For example, to write a lossless JPG2000 grid one would append
2816**+c**\ QUALITY=100\ **+c**\ REVERSIBLE=YES\ **+c**\ YCBCR420=NO
2817**Note**: You will have to specify a *nan* value for integer data types unless you wish that all NaN data values
2818should be replaced by zero.
2819
2820Consider setting :term:`IO_NC4_DEFLATION_LEVEL` to reduce file size and to further increase read/write performance.
2821Especially when working with subsets of global grids, masks, and grids with repeating grid values, the improvement is
2822usually significant.
2823
2824The NaN data value
2825------------------
2826
2827For a variety of data processing and plotting tasks there is a need to
2828acknowledge that a data point is missing or unassigned. In the "old
2829days", such information was passed by letting a value like -9999.99 take
2830on the special meaning of "this is not really a value, it is missing".
2831The problem with this scheme is that -9999.99 (or any other floating
2832point value) may be a perfectly reasonable data value and in such a
2833scenario would be skipped. The solution adopted in GMT is to use the
2834IEEE concept Not-a-Number (NaN) for this purpose. Mathematically, a NaN
2835is what you get if you do an undefined mathematical operation like
28360/0; in ASCII data files they appear as the textstring NaN. This
2837value is internally stored with a particular bit pattern defined by IEEE
2838so that special action can be taken when it is encountered by programs.
2839In particular, a standard library function called ``isnan`` is used to
2840test if a floating point is a NaN. GMT uses these tests extensively to
2841determine if a value is suitable for plotting or processing (if a NaN is
2842used in a calculation the result would become NaN as well). Data points
2843whose values equal NaN are not normally plotted (or plotted with the
2844special NaN color given in :doc:`/gmt.conf`). Several tools such as
2845:doc:`/xyz2grd`, :doc:`/gmtmath`, and
2846:doc:`/grdmath` can convert user data to NaN
2847and vice versa, thus facilitating arbitrary masking and clipping of data
2848sets. Note that a few computers do not have native IEEE hardware
2849support. At this point, this applies to some of the older Cray
2850super-computers. Users on such machines may have to adopt the old
2851'-9999.99' scheme to achieve the desired results.
2852
2853Data records that contain NaN values for the *x* or *y* columns (or the
2854*z* column for cases when 3-D Cartesian data are expected) are usually
2855skipped during reading. However, the presence of these bad records can
2856be interpreted in two different ways, and this behavior is controlled by
2857the :term:`IO_NAN_RECORDS` defaults parameter. The default setting (*gap*)
2858considers such records to indicate a gap in an otherwise continuous
2859series of points (e.g., a line), and programs can act upon this
2860information, e.g., not to draw a line across the gap or to break the
2861line into separate segments. The alternative setting (*bad*) makes no
2862such interpretation and simply reports back how many bad records were
2863skipped during reading; see Section :ref:`option_-g` for details.
2864
2865.. _Directory parameters:
2866
2867Directory parameters
2868--------------------
2869
2870GMT versions prior to GMT 5 relied solely on several environment variables
2871(**$GMT_SHAREDIR**, **$GMT_DATADIR**, **$GMT_USERDIR**, and **$GMT_TMPDIR**), pointing
2872to folders with data files and program settings. Beginning with version
28735, some of these locations are now (also or exclusively) configurable
2874with the :doc:`/gmtset` utility.
2875When an environment variable has an equivalent parameter in the :doc:`/gmt.conf` file,
2876then the parameter setting will take precedence over the environment variable.
2877
2878Variable **$GMT_SHAREDIR**
2879    was sometimes required in previous GMT versions to locate the GMT
2880    share directory where all run-time support files such as coastlines,
2881    custom symbols, PostScript macros, color tables, and much more reside.
2882    If this parameter is not set (default), GMT will make a reasonable
2883    guess of the location of its share folder. Setting this variable is
2884    usually not required and recommended only under special circumstances.
2885
2886Variable **$GMT_DATADIR** and parameter :term:`DIR_DATA`
2887    may point to one or more directories where large and/or widely used
2888    data files can be placed. All GMT programs look in these directories
2889    when a file is specified on the command line and it is not present in
2890    the current directory. This allows maintainers to consolidate large
2891    data files and to simplify scripting that use these files since the
2892    absolute path need not be specified. Separate multiple directories
2893    with commas. Any directory
2894    name that ends in a trailing slash (/) will be searched recursively
2895    (not under Windows).
2896
2897Variable **$GMT_USERDIR**
2898    may point to a directory where the user places custom configuration
2899    files (e.g., an alternate ``coastline.conf`` file, preferred default
2900    settings in ``gmt.conf``, custom symbols and color palettes, math
2901    macros for :doc:`/gmtmath` and :doc:`/grdmath`, and shorthands for
2902    gridfile extensions via ``gmt.io``). When **$GMT_USERDIR** is not defined,
2903    then the default value **$HOME**/.gmt will be assumed. Users may also place their own
2904    data files in this directory as GMT programs will search for files
2905    given on the command line in both :term:`DIR_DATA` and **$GMT_USERDIR**.
2906
2907Variable **$GMT_CACHEDIR**
2908    may point to a directory where the user places cached data files
2909    downloaded from the GMT data server. When **$GMT_CACHEDIR** is not defined,
2910    then the default value **$HOME**/.gmt/cache will be assumed. The cache
2911    directory can be emptied by running gmt **gmt clear cache**.
2912
2913Variable **$GMT_TMPDIR**
2914    may indicate the location, where GMT will write its state parameters
2915    via the two files ``gmt.history`` and ``gmt.conf``. If **$GMT_TMPDIR** is not
2916    set, these files are written to GMT session directory [for modern mode] or
2917    the current directory [for classic mode].
2918
2919Parameter :term:`DIR_DCW`
2920    specifies where to look for the optional Digital Charts of the World
2921    database (for country coloring or selections).
2922
2923Parameter :term:`DIR_GSHHG`
2924    specifies where to look for the required
2925    Global Self-consistent Hierarchical High-resolution Geography database.
2926
2927
2928Note that files whose full path is given will never be searched for in
2929any of these directories.
2930
2931Footnotes
2932---------
2933
2934.. [7]
2935   Vicenty, T. (1975), Direct and inverse solutions of geodesics on the
2936   ellipsoid with application of nested equations, *Surv. Rev.,
2937   XXII(176)*, 88–93.
2938
2939.. [8]
2940   PostScript definition. In the typesetting industry a slightly
2941   different definition of point (1/72.27 inch) is used, presumably to
2942   cause needless trouble.
2943
2944.. [9]
2945   Choose between SI and US default units by modifying in the
2946   GMT share directory.
2947
2948.. [10]
2949   To remain backwards compatible with GMT 4 we will also look for
2950   but only if cannot be found.
2951
2952.. [16]
2953   To keep PostScript files small, such comments are by default turned
2954   off; see :term:`PS_COMMENTS` to enable them.
2955
2956.. [17]
2957   For an overview of color systems such as HSV, see Chapter :doc:`colorspace`.
2958
2959.. [18]
2960   Convert other graphics formats to Sun ras format using GraphicsMagick's or ImageMagick's **convert** program.
2961
2962.. [19]
2963   Requires building GMT with GDAL.
2964