%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\chapter {Advanced Use of PLPLOT}\label{advanced}

In this chapter, we describe more precisely how to control the position
and scaling of a graph, how to alter the low-level line and character
attributes, and how to use the functions in PLPLOT for drawing
three-dimensional surface plots and contour plots.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section {Basic PLPLOT Concepts}

When drawing a graph, the programmer usually wishes to specify the
coordinates of the points to be plotted in terms of the values of the
variables involved. These coordinates are called {\em world coordinates}, 
and may have any floating-point value representable by the computer. The
{\em window\/} refers to the rectangular region of world-coordinate space
which is to be graphed. This window is mapped onto a rectangular region of
the {\em view surface}, which can be a terminal screen or a sheet of paper
in the output device (or a portion thereof, if subpages are being used).
This physical region onto which the window is mapped is called the {\em
viewport}. Before a graph can be drawn, the program must define both the
window and the viewport by calling appropriate routines in PLPLOT. 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section {Specifying the View Surface}

Before any actual plotting calls are made, a graphics program initialize
PLPLOT, i.e.~specify the output device and how this device is to be divided
up for graph plotting.  There are at present two routines recommended for
this purpose, \rou{plstar}, which prompts at the console for the output
device type, and \rou{plstart} which expects to be supplied the keyword of
the device as an argument.  The old routine {\tt plbeg} can also be used for
initialization, but use of this routine is discouraged since it requires the
device {\em number\/} which depends on the particular device drivers installed
for your system ({\tt plbeg} has only been retained for compatibility with
old codes, and will not be discussed further).

Besides selecting the device, {\tt plstar} and {\tt plstart} allow the user
to divide the output device plotting area into several subpages of equal
size, each of which can be used separately. The routine {\tt pladv} is used
to advance to a particular subpage or to the next subpage. The screen is
cleared (or a new piece of paper loaded) if a new subpage is requested
when there are no subpages left on the current page.  When a page is
divided into subpages, the default character, symbol and tick sizes are
scaled inversely as the square root of the number of subpages in the
vertical direction. 

A new addition to PLPLOT is the ability to write to multiple output streams.
An output stream corresponds to a single logical device to which one
plots independent of all other streams.  The function \rou{plsstrm}
is used to switch between streams (note one may only write to one output 
stream at a time).  At present, an output stream is not limited by the
type of device (however it may not be wise to attempt opening two terminal
devices).  Eventually it will be possible to open multiple output devices
per stream, with plots going to each device simultaneously, however this
feature was not ready in time for the PLPLOT 4.0 release.  An example
usage for the creation of multiple streams is as follows:

\begin{verbatim}
#include "plplot.h"

main()
{
    int nx = 2, ny = 2;

    plstart("xterm", nx, ny);

    <plots for stream 0>

    plsstrm(1);
    plsfnam("tst.plm");
    plstart("plmeta", nx, ny);

    <plots for stream 1>

    plsstrm(0);

    <plots for stream 0>
\end{verbatim}

and so on, for sending output simultaneously to an xterm and a metafile.
The default stream corresponds to stream number zero.  At present, the
majority of output drivers can only be used by a single stream (exceptions
include the metafile driver and X-window driver).  Also see example program
14 (note:  only the C version is available, although it can be done equally
well from Fortran).

At the end of a plotting program, it is important to close the plotting
device by calling \rou{plend}. This flushes any internal buffers and frees
any memory that may have been allocated, for all open output streams.  You
may call \rou{plend1} to close the plotting device for the current output
stream only.  Note that if PLPLOT is initialized more than once during a
program to change the output device, an automatic call to {\tt plend1} is
made before the new device is opened for the given stream.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section {Defining the Viewport} \label{viewport}

After defining the view surface, it is necessary to define the portion of
this surface which is to be used for plotting the graph (the viewport). All
lines and symbols (except for labels drawn by {\tt plbox}, {\tt plmtex} and
{\tt pllab}) are clipped at the viewport boundaries. 

Viewports are created within the current subpage. If the division of the
output device into equally sized subpages is inappropriate, it is best
to specify only a single subpage which occupies the entire output device
(by setting {\tt nx = 1} and {\tt ny = 1} in {\tt plstart} or {\tt plstar}), 
and use one of the viewport specification subroutines below to place the
plot in the desired position on the page.

There are four methods for specifying the viewport size, using the
subroutines \rou{plvpor}, \rou{plsvpa}, \rou{plvasp}, and \rou{plvpas}.
Each of these has the format:
\begin{verbatim}
    plvpor(xmin, xmax, ymin, ymax);
    plsvpa(xmin, xmax, ymin, ymax);
    plvasp(aspect);
    plvpas(xmin, xmax, ymin, ymax, aspect);
\end{verbatim}
where in the case of {\tt plvpor} and {\tt plvpas}, the arguments are given
in {\em normalized subpage coordinates\/} which are defined to run from 0.0
to 1.0 along each edge of the subpage. Thus for example,
\begin{verbatim}
    plvpor(0.0, 0.5, 0.5, 1.0);
\end{verbatim}
uses the top left quarter of the current subpage.

In order to get a graph of known physical size, the routine {\tt plsvpa}
defines the viewport in terms of absolute coordinates (millimetres) measured
from the bottom left-hand corner of the current subpage.  This routine
should only be used when the size of the view surface is known, and a
definite scaling is required.  

The routine {\tt plvasp} gives the largest viewport with the given aspect
ratio that fits in the current subpage (i.e. the ratio of the length of the
y axis to that of the x axis is equal to {\tt aspect}).  It also allocates
space on the left and top of the viewport for labels. 

The routine {\tt plvpas} gives the largest viewport with the given aspect
ratio that fits in the specified region (specified with normalized subpage
coordinates, as with {\tt plvpor}).  This routine is functionally
equivalent to {\tt plvpor} when a ``natural'' aspect ratio is chosen (done
by setting {\tt aspect} to 0.0).  Unlike {\tt plvasp}, this routine
reserves no extra space at the edges for labels. 

To help the user call {\tt plsvpa} correctly, the routine \rou{plgspa}
is provided which returns the positions of the extremities of the
current subpage measured in millimetres from the bottom left-hand corner
of the device. Thus, if to set up a viewport with a 10.0~mm margin
around it within the current subpage, the following sequence of calls
may be used
\begin{verbatim}
    plgspa(xmin, xmax, ymin, ymax);
    plsvpa(10.0, xmax-xmin-10.0, 10.0, ymax-ymin-10.0);
\end{verbatim}

A further routine \rou{plvsta} is available which sets up a standard
viewport within the current subpage with suitable margins on each side
of the viewport. This may be used for simple graphs, as it leaves enough
room for axis labels and a title. This standard viewport is that used by
{\tt plenv} (see Section \ref{plenv-sec}).

Another way to get a specified aspect ratio is via the routine
\rou{plsasp}, which sets the global aspect ratio and must be called prior
to {\tt plstar}.  An aspect ratio of 0.0 corresponds to ``natural''
dimensions (i.e.~fill the page); any positive value will give the specified
aspect ratio.  This scaling of plots is actually done in the driver, and so
may not work for all output devices (note that {\tt plrender} is capable of
scaled aspect ratio plots to any device whether that device supports
scaling or not).  In such scaled plots, absolute plotting is done in the
scaled coordinate system. 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section {Defining the Window} \label{window}

The window must be defined after the viewport in order to map the world
coordinate rectangle into the viewport rectangle. The routine
\rou{plwind} is used to specify the rectangle in world-coordinate space.
For example, if we wish to plot a graph showing the collector current
$I_C$ as a function of the collector to emitter voltage $V_{CE}$ for a
transistor where $0\le I_C\le 10.0\mbox{\, mA}$ and $0\le V_{CE}\le
12.0\mbox{\, V}$, we would call the function {\tt plwind} as follows:
\begin{verbatim}
    plwind(0.0, 12.0, 0.0, 10.0);
\end{verbatim}
Note that each of the arguments is a floating point number, and so the
decimal points are required. If the order of either the X~limits or
Y~limits is reversed, the corresponding axis will point in the opposite
sense, (i.e., right to left for X and top to bottom for Y). The window
must be defined before any calls to the routines which actually draw the
data points. Note however that {\tt plwind} may also be called to change
the window at any time. This will affect the appearance of objects drawn
later in the program, and is useful for drawing two or more graphs with
different axes on the same piece of paper.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section {Annotating the Viewport} \label{annotate}

The routine \rou{plbox} is used to specify whether a frame is drawn around
the viewport and to control the positions of the axis subdivisions and
numeric labels. For our simple graph of the transistor characteristics, 
we may wish to draw a frame consisting of lines on all four sides of the
viewport, and to place numeric labels along the bottom and left hand side.
We can also tell PLPLOT to choose a suitable tick interval and
the number of subticks between the major divisions based upon the
data range specified to {\tt plwind}. This is done using the following
statement
\begin{verbatim}
    plbox("bcnst", 0.0, 0, "bcnstv", 0.0, 0);
\end{verbatim}
Another routine \rou{pllab} provides for text labels for the bottom, 
left hand side and top of the viewport. These labels are not clipped, 
even though they lie outside the viewport (but they are clipped at the
subpage boundaries). {\tt pllab} actually calls the more general routine
{\tt plmtex} which can be used for plotting labels at any point relative
to the viewport. For our example, we may use
\begin{verbatim}
    pllab("V#dCE#u (Volts)", "I#dC#u (mA)", "TRANSISTOR CHARACTERISTICS");
\end{verbatim}
Note that \verb+#d+ and \verb+#u+ are escape sequences (see page
\pageref{escape}) which allow subscripts and superscripts to be used in
text.  They are described more fully later in this chapter.

The appearance of axis labels may be further altered by auxiliary calls to
\rou{plprec}, \rou{plschr}, \rou{plsxax}, \rou{plsyax}, and \rou{plszax}.
The routine {\tt plprec} is used to set the number of decimal places
precision for axis labels, while {\tt plschr} modifies the heights of
characters used for the axis and graph labels.  Routines {\tt plsxax}, {\tt
plsyax}, and {\tt plszax} are used to modify the {\tt digmax} setting for
each axis, which affects how floating point labels are formatted.

The {\tt digmax} variable represents the maximum field width for the
numeric labels on an axis (ignored if less than one).  If the numeric
labels as generated by PLPLOT exceed this width, then PLPLOT automatically
switches to floating point representation.  In this case the exponent will
be placed at the top left for a vertical axis on the left, top right for
a vertical axis on the right, and bottom right for a horizontal axis. 

For example, let's suppose that we have set {\tt digmax} $ = 5$ via {\tt
plsyax}, and for our plot a label is generated at {\tt y} $ = 0.0000478$.  In
this case the actual field width is longer than {\tt digmax}, so PLPLOT
switches to floating point.  In this representation, the label is printed as
simply $4.78$ with the $10^{-5}$ exponent placed separately.

The determination of maximum length (i.e.~{\tt digmax}) for fixed point
quantities is complicated by the fact that long fixed point representations
look much worse than the same sized floating point representation.
Further, a fixed point number with magnitude much less than one will
actually gain in precision when written as floating point.  There is some
compensation for this effect built into PLPLOT, thus the internal
representation for number of digits kept ({\tt digfix}) may not always
match the user's specfication (via {\tt digmax}).  However, it will always
be true that {\tt digfix} $\le$ {\tt digmax}.  The PLPLOT defaults are
set up such that good results are usually obtained without user
intervention. 

Finally, after the call to {\tt plbox}, the user may call routines
\rou{plgxax}, \rou{plgyax}, or \rou{plgzax} to obtain information about the
window just drawn.  This can be helpful when deciding where to put
captions.  For example, a typical usage would be to call {\tt plgyax} to
get the value of {\tt digits}, then offset the y axis caption by that amount
(plus a bit more) so that the caption ``floats'' just to the outside of the
numeric labels.  Note that the {\tt digits} value for each axis for the
current plot is not correct until {\em after\/} the call to {\tt plbox} is
complete. 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section {The Routine {\tt plenv}}\label{plenv-sec}

Having to call {\tt pladv}, {\tt plvpor}, {\tt plwind} and {\tt plbox}
is excessively cumbersome for drawing simple graphs. Subroutine {\tt plenv}
combines all four of these in one subroutine, using the
standard viewport, and a limited subset of the capabilities of {\tt plbox}.
For example, the graph described above could be initiated by the call:
\begin{verbatim}
    plenv(0.0, 12.0, 0.0, 10.0, 0, 0);
\end{verbatim}
which is equivalent to the following series of calls:
\begin{verbatim}
    pladv(0);
    plvsta();
    plwind(0.0, 12.0, 0.0, 10.0);
    plbox("bcnst", 0.0, 0, "bcnstv", 0.0, 0);
\end{verbatim}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section {Setting Line Attributes}

The graph drawing routines may be freely mixed with those described in
this section, allowing the user to control line color, width and styles.
The attributes set up by these routines apply modally, i.e, all subsequent
objects (lines, characters and symbols) plotted until the next change in
attributes are affected in the same way. The only exception to this rule
is that characters and symbols are not affected by a change in the line
style, but are always drawn using a continuous line.

Line color \label{color} is set using the routine \rou{plcol}. The argument
is ignored for devices which can only plot in one color, although some
terminals support line erasure by plotting in color zero. 

Line width \label{width} is set using \rou{plwid}. This option is not
supported by all devices.

Line style \label{style} is set using the routine \rou{plstyl}
or \rou{pllsty}. A broken
line is specified in terms of a repeated pattern consisting of marks
(pen down) and spaces (pen up). The arguments to this routine are
the number of elements in the line, followed by two pointers to
integer arrays specifying
the mark and space lengths in micrometers. Thus a line consisting of
long and short dashes of lengths 4\, mm and 2\, mm, separated by spaces of
length 1.5\, mm is specified by:
\begin{verbatim}
    mark[0] = 4000;
    mark[1] = 2000;
    space[0] = 1500;
    space[1] = 1500;
    plstyl(2, mark, space);
\end{verbatim}
To return to a continuous line, just call {\tt plstyl} with first argument
set to zero. You can use {\tt pllsty} to choose between 8 different
predefined styles.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section {Setting the Area Fill Pattern}

The routine \rou{plpat} can be used to set the area fill pattern. The
pattern consists of 1 or 2 sets of parallel lines with specified
inclinations and spacings. The arguments to this routine are the
number of sets to use (1 or 2) followed by two pointers to integer
arrays (of 1 or 2 elements) specifying the inclinations in tenths
of a degree and the spacing in micrometers. (The inclination should
be between -900 and 900.) Thus to specify an area fill pattern consisting
of horizontal lines spaced 2\, mm apart use:
\begin{verbatim}
    *inc = 0;
    *del = 2000;
    plpat(1, inc, del);
\end{verbatim}
To set up a symmetrical crosshatch pattern with lines directed 30 degrees
above and below the horizontal and spaced 1.5\, mm apart use:
\begin{verbatim}
    *inc = 300;
    *(inc+1) = -300;
    *del = 1500;
    *(del+1) = 1500;
    plpat(2, inc, del);
\end{verbatim}

The routine \rou{plpsty} can be used to select from 1 of 8 predefined
patterns.

The area fill routines also use the current line style, width and
colors to give a virtually infinite number of different patterns!

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section {Setting Character and Symbol Attributes}

There are two character sets included with PLPLOT. These are known as
the standard and extended character sets respectively. The standard
character set is a subset of the extended set. It contains 177
characters including the ascii characters in a normal style font, 
the greek alphabet and several plotter symbols. The extended character
set contains almost 1000 characters, including four font styles, 
and several math, musical and plotter symbols.

The standard character set is loaded into memory automatically when {\tt
plstar} or {\tt plstart} is called. The extended character set is loaded by
calling \rou{plfontld}.  The extended character set requires about 50
kbytes of memory, versus about 5 kbytes for the standard set. {\tt
plfontld} can be used to switch between the extended and standard sets
(one set is unloaded before the next is loaded).  {\tt plfontld} can be
called before {\tt plstar}.

When the extended character set is loaded there are four different font
styles to choose from.  In this case, the routine \rou{plfont} sets up the
default font for all character strings.  It may be overridden for any
portion of a string by using an escape sequence within the text, as
described below.  This routine has no effect when the standard font set is
loaded.  The default font (1) is simple and fastest to draw; the others are
useful for presentation plots on a high-resolution device.

The font codes are interpreted as follows:
\begin{itemize}
   \item{\tt font = 1}: normal simple font
   \item{\tt font = 2}: roman font
   \item{\tt font = 3}: italic font
   \item{\tt font = 4}: script font
\end{itemize}

The routine \rou{plschr} is used to set up the size of subsequent
characters drawn. The actual height of a character is the product of the
default character size and a scaling factor. If no call is made to
{\tt plschr}, the default character size is set up depending on the number
of subpages defined in the call to {\tt plstar} or {\tt plstart}, and the
scale is set to
1.0. Under normal circumstances, it is recommended that the user does not
alter the default height, but simply use the scale parameter. This can
be done by calling {\tt plschr} with {\tt def = 0.0} and {\tt scale} set to the
desired multiple of the default height. If the default height is to be
changed, {\tt def} is set to the new default height in millimetres, and
the new character height is again set to {\tt def} multiplied by {\tt
scale}.

The routine \rou{plssym} sets up the size of all subsequent symbols
drawn by calls to {\tt plpoin} and {\tt plsym}. It operates analogously
to {\tt plschr} as described above.

The lengths of major and minor ticks on the axes are set up by the routines
\rou{plsmaj} and \rou{plsmin}.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section {Escape Sequences in Text} \label{escape}

The routines which draw text all allow you to include escape sequences in
the text to be plotted. These are character sequences that are interpreted
as instructions to change fonts, draw superscripts and subscripts, draw
non-ASCII (e.g. Greek), and so on. All escape sequences start with a number
symbol (\verb+#+). 

The following escape sequences are defined:
\begin{itemize}
   \item \verb+#u+: move up to the superscript position
    (ended with \verb+#d+)
   \item \verb+#d+: move down to subscript position
    (ended with \verb+#u+)
   \item \verb+#b+: backspace (to allow overprinting)
   \item \verb+##+: number symbol
   \item \verb.#+.: toggle overline mode
   \item \verb.#-.: toggle underline mode
   \item \verb+#gx+: Greek letter corresponding to Roman letter {\tt x}
                     (see below)
   \item \verb+#fn+: switch to normal font
   \item \verb+#fr+: switch to Roman font
   \item \verb+#fi+: switch to italic font
   \item \verb+#fs+: switch to script font
   \item \verb+#(nnn)+: Hershey character nnn (1 to 4 decimal digits)
\end{itemize}

Sections of text can have an underline or overline appended. For example, 
the string
\[
{\rm\overline{S}(\underline{freq})}
\]
is obtained by specifying \verb."#+S#+(#-freq#-)"..

Greek letters are obtained by \verb+#g+ followed by a Roman letter.
Table~\ref{greek} shows how these letters map into Greek characters.
\begin{table}
   \centering
   \begin{tabular}{|l|*{12}{c|}}
   \hline
   Roman&A&B&G&D&E&Z&Y&H&I&K&L&M\\
   \hline
   Greek&A & B & $\Gamma$ & $\Delta$ & E & Z & H & $\Theta$ & I & K &
   $\Lambda$ & M \\
   \hline\hline
   Roman&N&C&O&P&R&S&T&U&F&X&Q&W\\
   \hline
   Greek&N & $\Xi$ & O & $\Pi$ & P & $\Sigma$ &
   T & $\Upsilon$ & $\Phi$ & X & $\Psi$ & $\Omega$ \\
   \hline\hline
   Roman&a&b&g&d&e&z&y&h&i&k&l&m\\
   \hline
   Greek&   $\alpha$ & $\beta$ & $\gamma$ & $\delta$ & $\epsilon$ & $\zeta$ &
   $\eta$ & $\theta$ & $\iota$ & $\kappa$ &
   $\lambda$ & $\mu$ \\
   \hline\hline
   Roman&n&c&o&p&r&s&t&u&f&x&q&w\\
   \hline
   Greek& $\nu$ & $\xi$ & o & $\pi$ & $\rho$ & $\sigma$ &
   $\tau$ & $\upsilon$ & $\phi$ & $\chi$ & $\psi$ & $\omega$ \\
   \hline
   \end{tabular}
\caption{Roman characters corresponding to Greek characters}
\label{greek}
\end{table}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section {Three Dimensional Surface Plots} \label{threed}

PLPLOT includes routines that will represent a single-valued function
of two variables as a surface. In this section, we shall assume that
the function to be plotted is {\tt Z[X][Y]}, where {\tt Z} represents
the dependent variable and {\tt X} and {\tt Y} represent the independent
variables.

As usual, we would like to refer to a three dimensional point {\tt (X, Y, Z)}
in terms of some meaningful user-specified coordinate system. These are
called {\em three-dimensional world coordinates}. We need to specify the
ranges of these coordinates, so that the entire surface is contained within the
cuboid defined by ${\tt xmin}<{\tt x}<{\tt xmax}$, 
${\tt ymin}<{\tt y}<{\tt ymax}$ and
${\tt zmin}<{\tt z}<{\tt zmax}$. Typically, we shall want to view the
surface from a variety of angles, and to facilitate this, a two-stage
mapping of the enclosing cuboid is performed. Firstly, it is mapped
into another cuboid called the {\em normalized box\/} whose size must also
be specified by the user, and secondly this normalized box is viewed from
a particular azimuth and elevation so that it can be projected onto the
two-dimensional window.

This two-stage transformation process allows considerable flexibility in
specifying how the surface is depicted. The lengths of the sides of the
normalized box are independent of the world coordinate ranges of each of the
variables, making it possible to use ``reasonable'' viewing angles even if the
ranges of the world coordinates on the axes are very different. The size of the
normalized box is determined essentially by the size of the two-dimensional
window into which it is to be mapped. The normalized box is centered about the
origin in the $x$ and $y$ directions, but rests on the plane ${\tt z = 0}$. It is
viewed by an observer located at altitude {\tt alt} and azimuth {\tt az}, where
both angles are measured in degrees. The altitude should be restricted to the
range zero to ninety degrees for proper operation, and represents the viewing
angle above the xy plane. The azimuth is defined so that when {\tt az = 0}, the
observer sees the xz plane face on, and as the angle is increased, the observer
moves clockwise around the box as viewed from above the xy plane. The azimuth
can take on any value.

The first step in drawing a surface plot is to decide on the size of the
two-dimensional window and the normalized box. For example, we could choose
the normalized box to have sides of length
\begin{verbatim}
    basex = 2.0;
    basey = 4.0;
    height = 3.0;
\end{verbatim}
A reasonable range for the $x$ coordinate of the two-dimensional
window is -2.5 to +2.5, since the length of the diagonal across the base of
the normalized box is $\sqrt{2^2+4^2} = 2\sqrt{5}$, which fits into this
coordinate range. A reasonable range for the $y$ coordinate of the two
dimensional window in this case is -2.5 to +4, as the the projection of the
normalized box lies in this range for the allowed range of viewing angles.

The routine \rou{plwind} or \rou{plenv} is used in the usual way
to establish the size of the two-dimensional window. The routine
\rou{plw3d} must then be called to establish the range of the three
dimensional world coordinates, the size of the normalized box and the
viewing angles. After calling {\tt plw3d}, the actual surface is
drawn by a call to \rou{plot3d}.

For example, if the three-dimensional world-coordinate ranges are
$-10.0\le{\tt x}\le 10.0$, $-3.0\le{\tt y}\le +7.0$ and
$0.0\le{\tt z}\le 8.0$, we could use the following statements:
\begin{verbatim}
    xmin2d = -2.5;
    xmax2d =  2.5;
    ymin2d = -2.5;
    ymax2d =  4.0;
    plenv(xmin2d, xmax2d, ymin2d, ymax2d, 0, -2);
    basex = 2.0;
    basey = 4.0;
    height = 3.0;
    xmin = -10.0;
    xmax = 10.0;
    ymin = -3.0;
    ymax = 7.0;
    zmin = 0.0;
    zmax = 8.0;
    alt = 45.0;
    az = 30.0;
    side = 1;
    plw3d(basex, basey, height, xmin, xmax, ymin, ymax, zmin, zmax, alt, az);
    plot3d(x, y, z, nx, ny, opt, side);
\end{verbatim}

The values of the function are stored in a two-dimensional array {\tt z[][]}
where the array element {\tt z[i][j]} contains the value of the function at
the point $x_i$, $y_j$.  (The two-dimensional array {\tt z} is a vectored
array instead of a fixed size array.  {\tt z} points to an array of pointers
which each point to a rwo of the matrix.) Note that the values of the
independent variables $x_i$ and $y_j$ do not need to be equally spaced, but
they must lie on a rectangular grid.  Thus two further arrays {\tt x[nx]}
and {\tt y[ny]} are required as arguments to {\tt plot3d} to specify the
values of the independent variables.  The values in the arrays x and y must
be strictly increasing with the index.  The argument {\tt opt} specifies how
the surface is outlined.  If {\tt opt = 1}, a line is drawn representing z as
a function of x for each value of y, if {\tt opt = 2}, a line is drawn
representing z as a function of y for each value of x, and if {\tt opt = 3}, a
net of lines is drawn.  The first two options may be preferable if one of
the independent variables is to be regarded as a parameter, whilst the third
is better for getting an overall picture of the surface.  If side is equal
to one then sides are drawn on the figure so that the graph doesn't appear
to float.

The routine \rou{plmesh} is similar to {\tt plot3d, } except that it is
used for drawing mesh plots. Mesh plots allow you to see both the top and
bottom sides of a surface mesh, while 3D plots allow you to see the top
side only (like looking at a solid object). The side option is not
available with {\tt plmesh.}

Labelling a three-dimensional or mesh plot is somewhat more complicated than
a two dimensional plot due to the need for skewing the characters in the
label so that they are parallel to the coordinate axes.  The routine
\rou{plbox3} thus combines the functions of box drawing and labelling.  Its
parameters are described more fully in Chapter \ref{reference}.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section {Contour Plots}\label{contour}

Several routines are available in PLPLOT which perform a contour plot of
data stored in a two-dimensional array.  A contour following algorithm is
used, so that it is possible to use non-continuous line styles.  Further, 
one may specify arbitrary coordinate mappings from array indices to world
coordinates, such as for contours in a polar coordinate system.  In this
case it is best to draw the distinction between a C and Fortran language
caller, so these are handled in turn. 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection {Contour Plots from C}

There are two routines callable from C for plotting contours, \rou{plcont}
and \rou{plconf}.  Routine {\tt plcont} has the form 
\name{plcont(z, nx, ny, kx, lx, ky, ly, clevel, nlevel, pltr)} 
where {\tt z} is the two-dimensional
array of size ${\tt nx}\times{\tt ny}$ containing samples of the function to
be contoured.  ({\tt z} is a vectored two-dimensional array as described in
the previous section.  It is {\em not\/} a fixed-size two-dimensional
array.) The parameters {\tt kx}, {\tt lx}, {\tt ky} and {\tt ly} specify the
portion of {\tt z} that is to be considered.  The array {\tt clevel} of
length {\tt nlevel} is a list of the desired contour levels.  Routine {\tt
plconf} has the form \name{plconf(z, nx, ny, kx, lx, ky, ly, clevel, nlevel,
pltr, xg, yg)} with all arguments identical to those in {\tt plcont} except
for the pointers to transformation arrays {\tt xg} and {\tt yg}.  These are
used as input to the transformation function {\tt pltr}.

The path of each contour is initially computed in terms of the values of the
array indicies which range from {\tt 0} to {\tt nx-1} in the
first index and from
{\tt 0} to {\tt ny-1} in the second index.
Before these can be drawn in the current
window (see page \pageref{window} in Section \ref{window}), it is
necessary to
convert from these array indicies into world coordinates. This is done by
passing a pointer to a user-defined function to {\tt plcont} (the case for
{\tt plconf} is slightly different and discussed below).  This
function pointer is the last argument {\tt pltr}.
This function must be declared as type {\tt void} in the
module which calls {\tt plcont}. This transformation function
must have the parameter list
\name{void pltr(x, y, tx, ty);}
where {\tt (x, y)}
is the point through which the contour runs expressed in terms of array
indicies, and {\tt (tx, ty)} are pointers to float variables which are the
world coordinates of the point which corresponds to these indicies.

Often, the transformation between array indices and world coordinates can be
expressed as a linear transformation.  A routine is provided within the
library which can be passed to {\tt plcont} as {\tt pltr}.  This
transformation routine is
\begin{verbatim}
#include "plplot.h"

#ifdef PLSTDC
void 
xform(PLFLT x, PLFLT y, PLFLT * tx, PLFLT * ty)
#else
void 
xform(x, y, tx, ty)
PLFLT x, y, *tx, *ty;
#endif
{
    *tx = tr[0] * x + tr[1] * y + tr[2];
    *ty = tr[3] * x + tr[4] * y + tr[5];
}
\end{verbatim}
and should be compiled as part of the user's code (it is {\em not\/}
normally linked in with the PLPLOT library since the {\tt tr} data array is
unspecified).

Thus by setting up the values in the array {\tt tr[]}, we can
apply an arbitrary translation, rotation and/or shear to the array before
drawing out the contours. By defining other transformation subroutines, 
it is possible to draw contours wrapped around polar grids etc.  If no
transformation is required, you can simply set {\tt tr[0]$ = $tr[4]$ = $1.}, 
with other entries set to $0.$.  Alternately you can pass the built-in
function {\tt pltr0} to {\tt plcont}; this function merely sets {\tt *tx}
to {\tt x} and {\tt *ty} to {y}, resulting in no net transformation.

As an example in setting up {\tt tr[]}, suppose that the array {\tt z}
is of size $21 \times 41$ and contains the values of the function
$z[x][y]$, 
where $x$ ranges from 0.0 to 4.0 and $y$ ranges from -8.0 to 8.0.
Furthermore, 
let us also suppose that the window (as defined using {\tt plenv} or
{\tt plwind}) covers this range of world coordinates.
Since we wish the index
(0, 0) in array {\tt z} to map to (0.0, -8.0) and the index (20, 40) to map
to (4.0, 8.0), and for there to be no skew in the axes, we should choose
elements of {\tt tr[]} so that
\[
   \begin{array}{l@{\; = \;}l}
   tx & 0.2x \\
   ty & 0.4y - 8.
   \end{array}
\]
and so {\tt tr[0] = 0.2}, {\tt tr[1] = 0.0}, {\tt tr[2] = 0.0}, 
{\tt tr[3] = 0.0}, {\tt tr[4] = 0.4}, {\tt tr[5] = -8.}.

For routine {\tt plconf}, the user must pass pointers to transformation
arrays as well as the function pointer.  The use of transformation arrays
is generally the most convenient and flexible way to map coordinates, since
the mapping function (which only handles interpolation) need not change
from one problem to the next.  In this case there are two built-in
transformation functions to assist the user; these are:
\name{void pltr1(x, y, tx, ty, xg, yg, nx, ny);}
\name{void pltr2(x, y, tx, ty, xg, yg, nx, ny);}
where {\tt (xg, yg)} are pointers to the transformation arrays and {\tt
(nx, ny)} are the number of gridpoints in each dimension.  These functions
handle all necessary interpolations to calculate coordinate values between
grid points.  The transformation arrays passed to {\tt pltr1} must be
functions of a single variable only ({\tt xg[i], yg[i]}), while those
passed to {\tt pltr2} must be functions of two variables ({\tt
xg[i, j], yg[i, j]}).  This is further discussed in the following section.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection {Contour Plots from Fortran}

The routines mentioned above are not recommended for use directly from
Fortran due to the need to pass a function pointer.  That is, the
transformation function is written in C and can not generally be changed by
the user.  The call for routine {\tt plcont} from Fortran is then
\name{call plcont(z, nx, ny, kx, lx, ky, ly, clevel, nlevel, tr)} 
where {\tt tr} is a 6 element array with the coefficients for the
transformation function {\tt xform} given above and all other arguments are
the same as in the call from C (see above discussion of {\tt plcont}). 

The three routines recommended for use from Fortran are
\rou{plcon0}, \rou{plcon1}, and \rou{plcon2}.  These routines are similar to
existing commercial plot package contour plotters in that they offer
successively higher complexity, with {\tt plcon0} utilizing no
transformation arrays, while those used by {\tt plcon1} and {\tt plcon2} 
are one and two dimensional, respectively.  The call syntax for each is
\name{call plcon0(z, nx, ny, kx, lx, ky, ly, clevel, nlevel)} 
\name{call plcon1(z, nx, ny, kx, lx, ky, ly, clevel, nlevel, xg1, yg1)} 
\name{call plcon2(z, nx, ny, kx, lx, ky, ly, clevel, nlevel, xg2, yg2)} 
The {\tt plcon0} routine is implemented via a call to {\tt plcont} with a
very simple (identity) transformation function, while {\tt plcon1} and {\tt
plcon2} use interpolating transformation functions in a call to {\tt
plconf}.

The transformation arrays are used by these routines to specify a mapping
between the computational coordinate system and the physical one.  For
example, the transformation to polar coordinates might look like :
\begin{verbatim}
    do i = 1, NX
        do j = 1, NY
            xg(i, j) = r(i) * cos( theta(j) )
            yg(i, j) = r(i) * sin( theta(j) )
        enddo
    enddo
\end{verbatim}
assuming the user had already set up arrays {\tt r} and {\tt theta} to
specify the $(r, \theta)$ values at the gridpoints in his system.  For this
example, it is recommended that the user add an additional cell in theta
such that {\tt xg(i, NY+1) = xg(i, 1)} and {\tt yg(i, NY+1) = yg(i, 1)} so
that the contours show the proper periodic behavior in $\theta$ (see also
example program 9).

The transformation function not only specifies the transformation at grid
points, but also at intermediate locations, via linear interpolation.  For
example, in the {\tt pltr1} transformation function used by {\tt plcon1}, 
the 1-d interpolation to get {\tt tx} as a function of {\tt x} 
looks like (in C) :
%
\begin{verbatim}
    ul = (PLINT)x;
    ur = ul + 1;
    du = x - ul;

    xl = *(xg+ul);
    xr = *(xg+ur);

    *tx = xl * (1-du)  +  xr * du;
\end{verbatim}
%
while in Fortran this might look like:
%
\begin{verbatim}
    lxl = x
    lxr = lxl + 1
    dx = x - lxl

    xl = xg(lxl)
    xr = xg(lxr)

    tx = xl * (1-dx)  +  xr * dx
\end{verbatim}
