%%%
%
% A latex document that describes how to use the AthenaTools plotter
% widget set.
%
% $Id: Using.tex,v 1.1 91/08/22 15:38:04 gnb Exp $ 
%
% $Source: /export/data/sources/x/At/Plotter/RCS/Using.tex,v $
%
% $Log:	Using.tex,v $
% Revision 1.1  91/08/22  15:38:04  gnb
% Initial revision
% 
%
% Copyright 1991 by Burdett, Buckeridge & Young Ltd.
%
% All rights reserved.
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for any purpose and without fee is hereby granted,
% provided that the above copyright notice appear in all copies and that
% both that copyright notice and this permission notice appear in
% supporting documentation, and that the name of Burdett, Buckeridge &
% Young Ltd. (BBY) not be used in advertising or publicity pertaining to
% distribution of the software without specific, written prior
% permission.
% 
% BBY DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
% ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
% BBY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
% ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
% WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
% ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
% SOFTWARE.
% 
%
%\documentstyle[a4wide,newcen,tgrind]{article}
\documentstyle[a4wide,newcen,tgrind]{article}
\title{Using the AthenaTools Plotter Widget Set \\
	(Version 5)}
\author{Gregory Bond \\ Burdett, Buckeridge \& Young Ltd. \\
	{\tt gnb@bby.oz.au}}
\date{14th August, 1991 \\ Last Change: \verb$Date: 91/08/22 15:38:04 $ }
\newcommand{\nyi}{\footnote{This feature is not yet implemented.}}
\begin{document}
\maketitle

\section{Introduction}

This document is supposed to be an overview document and describes how
to use the Athena Tools plotter widget set to add graphs to your X
programs.  It is assumed the reader is familiar with general X Toolkit
programming and widget sets in general.  Most of the detailed
information regarding resources etc. is documented in the relevant man
pages.

The Athena Tools Plotter Widget set provides many of the features
business and scientific users need in a graph that will be embedded in
another program.  Some highlights:

\begin{itemize}
\item
Line and Bar graphs for business-style graphics.

\item
Scatter, X-Y and Contour plots for scientific style graphics\nyi .

\item
Automatic or manual scaling of axis values, automatic selection of tic
and subtic points.

\item
Very flexible text facilities, including math symbols, sub- and
super-scripts, font changes etc.  This text facility can be used for
legend names, graph titles, axis labels, tic labels, or attached to
arbitrary points on the graph in either pixel space or user space.

\item
Unlimited number of plots on each graph, with each plot independently
specified.  (Each plot on the graph is a different widget).

\item
Encapsulated PostScript generated that closely matches the screen
output. Color postscript will be added when I get a color Postscript
printer to test it on!

\item
Log\nyi\ or linear axes, or axis labeled at arbitrary points with
arbitrary strings (which is very useful for labeling axes with dates,
for example).

\item
Very flexible axis handling.  There are four axes on the graph, and
any plot can be associated with either X axis and either Y axis.

\item
``Frame'' axes that get their scaling etc.\ from another axis Object,
on either the same or another graph.  This makes coordination between
related graphs very easy.

\item
A Fast Update mode that can quickly redraw rapidly-changing
data\footnote{This is implemented but untested at this point in time}.

\item
Easy access to application data.  The widget set is designed to access
application data that is stored in an array of structures; it can pull
data out of structures in either Float, Double or Integer
format\footnote{Other data types are easily added}.

\item
Registration functions for use with the Widget Creation
Library\footnote{A rapid prototyping and development tool, available
from comp.sources.x archives (Volume 11, Issues 13-50) and ftp from
export.lcs.mit.edu and devvax.jpl.nasa.gov.}.
\end{itemize}

This is a complete redevelopment from the Version 4 of the AthenaTools
plotter Widget. It is only partially upwards compatible.  See Section
\ref{history} for more details.

\subsection{What it it Not}

The Plotter widget is a widget and is not intended for stand-alone
graphing applications (use GNUplot or similar for that).  It is not a
3D library, and is not really a replacement for Harvard Graphics or
some such.  It cannot do Pie charts or other non-XY type graphs.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Usage Walkthrough}
\label{walkthrough}
This section explains what sort of data the plotter expects from your
application, and gives a quick overview of how to program using these
widgets.  The example in this section is from {\tt sample\_prog.c},
the test program that came with the source; you can make and run this
program by typing {\tt make sample\_prog} in the source
directory.\footnote{Don't confuse this with the {\tt test.c} file,
referred to below as the test program, which required Wcl to use and
demonstrates more sophisticated features.} This program is written in C
and uses no resource files.  This means anyone should be able to
compile and run it.  Of course, you wouldn't actually write
applications this way, would you?\footnote{No, of course you wouldn't.
You would use a UI builder or UIL, if you can get them to accept
third-party widgets.  Or you would use Wcl.} You should be able to
transfer the concepts to your favourite development environment with
no problems.  A listing of the sample\_prog.c file is included in
Section \ref{sampleprog}.

Figure \ref{fig:sample} shows the PostScript output from a typical use of
the plotter widget.  This was generated by hitting the ``Print''
button on the sample program\footnote{And then deleting the trailing
``showpage'' as my dvi2ps converter doesn't handle it properly.}.
%
\begin{figure}
  \begin{center}
    \input{Sample.tex}
  \end{center}
  \caption{\label{fig:sample}Sample Output From Plotter Widget}
\end{figure}

The general arrangement is as follows.  For each graph, you create a
single AtPlotter widget.  This is a Widget, and has an X window, the
same as most other widgets.  You then create some axis objects (some
subclass of AtAxisCore, usually AtAxis) as children of the AtPlotter
and attach them to the parent by doing an {\tt XtSetValues()} using
the {\tt XtNxAxis} and similar resources.  Then, for each data item to
wish to plot on this graph, you create a plot object (a subclass of
AtPlot, usually also a subclass of AtSPlot, such as AtLinePlot).  You
then use the member functions for that plot object to attach it to
your application data.  When the AtPlotter is first displayed, it will
automatically calculate all the bounds, scaling etc and display the
graph. 

In contrast to the previous releases of this widget set, this version
doesn't require copies of the data.  Instead, providing your
application is suitably arranged, the plot widgets can read the
information straight out of your existing structures.  The assumption
is your application data is stored in an array of structures.  

As an example, consider the sample program, a simple accounting
application for a Widget distribution company.  You might wish to
display the weekly sales and profit figures for the sale of Widgets
for the past year.  But your database stores only the volume sold, the
sale price and the purchase price.  So you would declare a structure
like this:

\begin{verbatim}
     struct profits {
         /* From database */
         long volume;
         float buy_price;
         float sell_price;
         /* calculated values */
         double sales;
         double cost;
         double profit;
     };
\end{verbatim}

You would then declare an array of 52 structs:
\begin{verbatim}
    #define NUM_WEEKS 52
    struct profits profits[NUM_WEEKS];
\end{verbatim}
Two routines (called {\tt read\_from\_database()} and {\tt
calculate\_profits()} in the sample program) could read in the weekly
figures from the database and run through a loop to calculate sales,
cost and profits for each week.  This creates the data to be plotted.

Next we need to write the code to create the plotter and its children.
The routine {\tt make\_plotter()} does that.  It creates the main
plotter, then the three axes (X axis for the week number, Y axis for
profit, and Y2 axis (on the right hand side) for volume).  Then it
creates the two plots, a AtLinePlot for profits and a AtBarPlot for
volume.

The {\tt make\_form()} routine and associated callbacks just give two
buttons above the plot, one to exit the program, and one used to
create the PostScript file that was included as Figure
\ref{fig:sample} above.

The most interesting bit is attaching the application data to the
plot objects. This is what the {\tt attach\_data()} routine does.
The relevant routine, {\tt AtLinePlotAttachData},\footnote{This
routine is just a {\tt \#define}'d alias for the routine {\tt
AtSPlotAttachData}.} is a member routine of the AtLinePlot
widget widget class.  Once you have created your AtLinePlot widget for
displaying the profit, you would attach the data using a call like
this:
\begin{verbatim}
AtLinePlotAttachData(line, (XtPointer) &profits[0].profit,
                      AtDouble, sizeof (struct profits), 1, NUM_WEEKS);
\end{verbatim}

The parameters are as follows:

\begin{enumerate}
\item
The widget (a subclass of AtSPlot) you are attaching the data to.

\item
A pointer to the first data item.

\item
The type of that item (an enumerated type defined in {\tt
<At/SPlot.h>}); current values are {\tt AtDouble}, {\tt AtFloat} and
{\tt AtInt}.  Adding extra data types is simple.

\item
A parameter called the Stride, which is the number of bytes between
successive data items.  In most applications, that will be the size of
the structure you are accessing.  Other possible values would be {\tt
sizeof(double)} if your data was in a simple array of doubles, or {\tt
5 * sizeof (struct profits)} if your array was of daily data and you
only wanted to plot Fridays data.

\item
The integer X axis value of the first item in the list (often 0 or 1
but not always).

\item
The number of items in the list. The X axis value of the last item
will be (start + num - 1).
\end{enumerate}

The data pointed to in this routine should remain valid until the
next attach call is made (as it may be accessed if the window resizes
or if other plots change or if PostScript output is generated).
Setting the address to NULL and the count to 0 will effectively
undisplay the plot.

If the underlying data has changes, a new call to the attach routine
should be made so that the change is noted and new bounds calculated.

The volume data is attached to the AtBarPlot widget with the equivalent
call\footnote{The {\tt AtBarPlotAttachData} is also a {\tt
\#define}'d alias for {\tt AtSPlotAttachData}.}:
\begin{verbatim}
AtBarPlotAttachData(bar, (XtPointer) &results[0].volume,
                     AtInt, sizeof (struct profits), 0, 52);
\end{verbatim}

Once the {\tt XtMainLoop()} routine is called, the graph magically
appears.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{More Detail}
\subsection{Definitions}

Lets start by defining some terms so we all understand what we are
talking about.

\begin{description}
\item[Object]
Any X Toolkit Intrinsics object that is a subclass of the Object class.
XtSetValues operates on Objects and XtCreateWidget creates them.

\item[Widget]
Any Object that is a subclass of Core and thus has a window.

\item[Graph]
The entire display of a Plotter widget.  Includes the main plotter
widget and all children.  There can be multiple graphs, and hence
multiple AtPlotter widgets, in one program.

\item[Plot]
A single data Object plotted on a graph.  (i.e. a single line or bar
plot). One AtPlot Object per plot, multiple plots per graph.

\item[User Space, Pixel Space]
User space is the realm of real numbers that the graph is attempting
to plot.  Pixel space is the screen coordinates that X windows works
in.  All application data is expressed in user space, and is converted
to pixel space (or pixel locations) by the various recalc routines
inside the plotter.  Application programmers should deal with user
space only, and not need to touch pixel space.

\item[Refresh]
Simply redraw one plot on the graph.  No screen clear or redraw of
other child Objects required.

\item[Redraw]
Simply refresh the on screen image of the whole plotter widget. No
calculation required.

\item[Relayout]
The pixel dimensions of the graph widget have changed (e.g. because
the user resized the application) or the size of one of the component
parts (e.g. an axis is wider because the font changed), but the data
that is plotted is unchanged.

\item[Rescale]
The data has changed and the existing axis bounds are not
sufficient.  New axis bounds are required, but no layout has
changed and all axes are in the same spot.  Is concerned with
min/max of axis values, tic values and intervals etc.

\item[Recalc]
Either pixel location or data has changed for a plot, and the
cached pixel values need to be recalculated.  Can be for a single
child or the whole graph.

\end{description}

A rescale implies a recalc, and a relayout implies a recalc, but
relayout and rescale are orthogonal (i.e. one doesn't necessarily
imply the other).  A recalc implies a redraw.

\subsection{Widget Class Hierarchy}

Figure \ref{fig:classes} shows the class inheritance of the Plotter widget set.
%
\begin{figure}
  \begin{center}
    \input{classes.tex}
  \end{center}
  \caption{\label{fig:classes}The Plotter Widget Set Class Hierarchy}
\end{figure}
%
As can be seen, most of the widgets in the set are actually Objects
and don't have an X window of their own.  They draw on the the window
supplied by the parent AtPlotter widget.  A minimal graph includes a
single AtPlotter widget that is the parent of two Objects
that are subclasses of AtAxisCore, and one Object that is a subclass of
AtSPlot. 

The AtPlot, AtSPlot and AtAxisCore widget classes are simply
placeholders for some logic and resources; you shouldn't ever need to
make Objects of these types.  The AtPlotter will only accept children
that are a subclass of AtPlot, and AtPlot classes will only accept
AtPlotter widgets as a parent.

\subsection{Elements of the Graph}
Figure \ref{fig:layout} shows the various areas of the graph.
%
\begin{figure}
  \begin{center}
    \input{layout.tex}
  \end{center}
  \caption{Elements Of The Plotter Window\label{fig:layout}}
\end{figure}
%
We will examine each of the elements in turn.

The string along the top is known as the title.  The font, size, color
and style (i.e. roman, {\it italic}, {\bf bold} etc.) and the string
itself can be set using resources of the AtPlotter widget. The font
family (see section \ref{fontfamily}) is the same for all the strings
in the AtPlotter widget.  Specifying a title as the empty string
removes the title and reclaims the space for the main part of the
graph.

Along the right hand edge of the graph is the legend.  The AtPlotter
maintains details about the legend as Constraint resources on behalf
of the children.  The AtPlotter has resources to set the string, size
and style of the legend title, as well as the size and style of the
legend labels (``Plot A'' and ``Plot B'' in this case).  The color of
the text in the legend is set in the AtPlotter and affects all the
text in the legend.  The actual legend strings are constraint
resources and belong (logically) to the child.  Each item (apart from
the title) in the legend is drawn by the child plot, and exactly
matches the corresponding plot in the main graph area.  The legend is
controlled by the AtPlotter widget, and the resource {\tt
XtNdrawLegend} controls whether it is displayed.

There are three axes used in the sample graph.  The vertical axes are
of class AtAxis, and all the values displayed on these axes were
calculated automatically (although you can manually set the maximum,
minimum and the distance between tic marks if required).  There are 9
tics on the left-hand vertical axis.  Each tic has a label and a grid
line associated with it.  The color of the axis, the font, size and
style of the tic labels and a {\tt sprintf}(1) format string and
multiplier for generating the tic labels can be specified.  The
automatic tic calculation considers the size of the labels and the tic
density resource to decide how many tics to display.

The small marks between the tic values are called subtics and
they are automatically generated, whether the main ticks are manually
or automatically set.  The subtic density resource can increase or
decrease the number of subtics per tic, and care is taken that the
number is sensible (e.g. power of 2 or 5 etc).

There is a label associated with each axis, again an arbitrary text
string in any font, color or style.  For vertical axes it is rotated
90 degrees. These are the labels ``Profits (\$1,000s)'', ``Volume
Shipped (1,000s)'' and ``Week Number'' in the sample graph.

In general, there are four axes on the graph.  The horizontal axes are
the X axes, the lower is known as the X axis and the upper as the X2
axis.  The vertical axes are Y axes, the left being Y axis and the right
being Y2 axis.  Each plot on the graph is associated with one X axis
and one Y axis.  The AtPlotter maintains constraint resources on
behalf of each plot child to decide which X and Y axis it is
associated with.  If there are no plot children associated with an
axis (as is the case for the Y and X2 axes in this example), then
there is no need for an axis widget to be created for that axis.

The X2 and Y2 axes are known as mirror axes, and the AtAxisCore
resource {\tt XtNmirror} {\em must} be set on axes used for these axes
and {\em must not} be set on axes used for the X axis and Y axis.
Similarly, the AtAxisCore resource {\tt XtNvertical} {\em must} be set
on axes used for the Y axis and Y2 axis, and {\em must not} be set on
axes used for the X axis and X2 axis.  Both {\tt XtNmirror} and {\tt
XtNvertical} resources can be set at Object creation time only; any
attempt to change them will fail with a warning message.

The AtAxisCore widget is a placeholder for most of the axis resources,
and also contains the logic for calculating pixel values from
user-space values.  It relies on subclass member functions to decide
what values to use for minimum and maximum, at what values to place
tic and subtic marks, and the labels associated with those tic marks.
The AtAxisCore widget then handles all the pixel conversions and
screen and PostScript redrawing, so the axis classes are very simple
to implement.

When the AtPlotter widget is created, it does {\em not} create any
child axes\footnote{This is a change in behaviour since Version 4.}.
It is the programmers responsibility to create (at least) two
AtAxisCore Objects and attach them to the AtPlotter (using {\tt
XtSetValues} and the {XtNxAxis} and similar resources).  Nasty things
happen if this isn't done (i.e. the program exits via {\tt
XtAppError()}).  It {\em is} possible to have axis children that are
not one of the currently used axes, but they must not be displayed
(i.e. must have {\tt XtNdisplayed} = False).  This is useful for
having several possible axes on a plot (e.g. an AtAxis if it is used
for scaling a plot, or a AtFrameAxis to carry tic marks when the
opposite axis is being used), and to swap between them with calls to
{\tt XtSetValues()} using for example the {\tt XtNx2Axis} resource.

Also on the sample graph are two plots: an AtLinePlot and an
AtBarPlot.  For these plots, the color, line style and line thickness
can be set.  This effects both the main plot and the legend entry for
that plot.  For the AtBarPlot, the interior of the bars can either be
the same color as the outline, or a different color.  The interior
area can also be stippled with one of 11 stipples\footnote{Only 5
distinct on-screen stipple patterns are implemented at the moment,
pending discovery of good ``10\% gray'' sort of stipples.  The 11
stipples {\tt GRAY0} through {\tt GRAY10} correspond to PostScript
{1.0 setgray} down to {0.0 setgray} constructs.} that will be
converted to a grayscale level on PostScript output.  Ether the
outline or the interior fill can be disabled (but, obviously, not
both).  by default, the AtBarPlot bars for X-Axis value $x$ run from
$[x, x+1)$.  This can be changed by setting the {\tt XtNcellOffset}
and {\tt XtNcellWidth} resources, so overlapping bar graphs (in the
style sometimes known as ``Stacked Bar'' graphs, see Figure
\ref{fig:bars}) can be drawn.

{\Large\it NOTE}:
All Objects that are not subclasses of rectObj (and that includes all
the AtPlot Objects) do {\em not} have a managed flag.  Hence they
should {\em never} be managed children of the AtPlotter widget.  This
means they should be created with {\tt XtCreateWidget()} and not {\tt
XtCreateManagedWidget}, and should never be the argument to the {\tt
XtManageChild()} routine.  Attempts to manage non-rectObjs will
corrupt the instance record with undefined results.

WCL users should note that, until (if ever) Wcl has a facility to
register Objects as unmanageable, the default will be to manage all
children.  This will require a set of resources similar to the following:
\begin{verbatim}
	*AtPlotter*wcManaged:      False
	*AtPlotter.wcManaged:      True
\end{verbatim}
to stop the Wcl creation routines from automatically managing the
children of all AtPlotter widgets as they are created.

Rather than use {\tt XtManageChild()} and the {\tt XtNmappedWhenManaged}
flag to display plots and axes, the parent AtPlotter maintains a
constraint variable for each child called {\tt displayed}.  Setting
this to false has the same effect that calling {XtUnmanageChild()}
with the {\tt XtNmappedWhenManaged} flag set would have on a normal
widget, i.e. the child would disappear and take no part in the
calculation of axes bounds etc.  It is an error to undisplay an axis
that still has child plots associated with it, and undefined results
occur if a normal (as opposed to frame) axis is displayed without
children associated with it.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Advanced Topics}
  
\subsection{Text Facilities}
\label{fontfamily}

All text strings in the plotter widget set are implemented using the
AtText facility.  This is in the style of Motif compound XmString
type.  It is a unified set of routines that allows easy
specification of text styles, multiple fonts and sizes as well as
symbols, and PostScript output that closely matches the on-screen
version.  See the {\tt AtText}(3) man page for the full details.

Each string segment is make up from five elements: the font family,
the style, the size, and the text.  The font family is something like
``times'' and specifies the basic look of the font.  The style
specifies plain, {\it italic\/}, {\bf bold} or {\sl bolditalic}
typeface.  The size ranges from {\tiny\tt SMALLEST} (about 8 point) to
{\LARGE\tt BIGGEST} (about 24 point).  Each segment is a simple list of
characters in that font/face/size combination.

The routine that compiles Strings to the AtText structs has facilities
for interpreting escapes to change fonts etc, so a resource
specification like
\begin{verbatim}
*title:  @g{D}V/@g{d}@i{t} versus. @aleph@-{@smaller<0>}
\end{verbatim}
will give a title that looks rather like
\begin{quote}
$\Delta$ V / $\delta i$ versus. $\aleph_{0}$
\end{quote}

In this widget set, the font family is set once per Object, but the
size and style can be changed on a per-string basis.  (This avoids the
possibility of the so-called ``ransom note'' look).

\subsection{The Layout Procedure}

This is the sequence of steps the plotter goes through to lay out a graph.

\begin{enumerate}
\item
The X and Y range for each plot child is accumulated and remembered
as data is attached to or changed for each child.

\item
The X and Y ranges of all the child plots are merged, on the basis of
the {\tt XtNuseX2Axis} and {\tt XtNuseY2Axis} resources, into a simple
bounding box for all four axes.  (One X axis and one Y axis may be
unused at this stage).

\item
\label{minmax}
Each axis currently in use is in turn offered its minimum and maximum
(calculated above) via a call to the AtAxis member function {\tt
AtAxisAskRange}.  It is the responsibility of this routine to do any
rounding, communication etc. as required, and the returned minimum and
maximum are used by the plotter.  There is a callback list on the
AtAxisCore Object ({\tt XtNrangeCallback}) that is called by the
AtAxisCore code after it has decided on the axis bounds.  This
programmer-written routine can modify the minimum, maximum, number
width and tic interval values as required.  This is used for linking
graphs (see Section \ref{linking}).  The calculated number width
(which may be approximate only at this stage) is used to calculate the
``width'' of the axis (which is the amount of the axis that is outside
the main graph area).

\item
A layout is done, assuming the axis widths calculated in step
\ref{minmax} are accurate.  This sets the position of all the graph
components within the main AtPlotter window.

\item
Each of the active axes is positioned by a call to the {\tt
AtAxisSetLocation} member function.  If the length of the axis changes
significantly (currently by 10\%), then it is assumed the number of
relevant tics might have changed, thus changing the rounding and
endpoints of the axis.  If this is the case, the process is repeated
at step \ref{minmax}.  Should not loop more than twice at this point,
assuming step \ref{minmax} can do a reasonable guess for the axis
width.

\item
Each of the axes is recalculated by a call to the AtPlot {\tt
AtPlotRecalc} member function.  Most of the arguments to the recalc
function for axis objects are ignored.  This step may give a better
guess as to things like the number width, which changes the layout.
If so, the sequence restarts at step \ref{minmax}.  Some care is taken
to avoid infinite loops.

\item
Each of the non-axis child plots is recalculated by a call to the {\tt
AtPlotRecalc} routine, with the scales being extracted from the
already-recalculated axes as appropriate.

\item
All children in the graph are redisplayed.
\end{enumerate}

All of this is controlled by one routine which is the redraw routine
for the AtPlotter class.  All requests are remembered and stored up,
so the above procedure is only done when necessary.  This means a
program can change several things one after the other, and the graph
will only do the expensive layout and redraw calculation once, not
once per change.  This is faster and reduces flickering.

Furthermore, much care is taken internally to avoid as much of the
above sequence as is possible, so that if small things change,
minimal calculation and redrawing is done.

\subsection{Drawing Order}

The order in which the children of the AtPlotter widget are drawn
affects which is ``above'' (and hence obscures) which in the display.
The first one drawn is conceptually on the bottom, as you would
expect.  (In this context, ``children'' refers to all children, both
axes and plots).  There are three typical situations where this is
relevant:
\begin{itemize}
\item
Generally the grid provided by the axes should be below the plotted
data.

\item
When drawing line plots and bar plots on the same graph, you want the
AtLinePlot to be drawn second so that they are visible and not obscured
by the bars (as in the sample plot).  Otherwise, the information from
the line graph will likely be hidden.

\item
Several bar plots can create the ``stacked bar'' effect by drawing
them in sequence, and arranging them to overlap slightly.  The sample
in Figure \ref{fig:bars} shows what this looks like.
\begin{figure}
  \begin{center}
    \input{bars.tex}
  \end{center}
  \caption{``Stacked Bar'' style plot\label{fig:bars}}
\end{figure}
All three AtBarPlots have the {\tt XtNcellWidth} resource set to 0.3 (so
they take 0.3 of a cell each).  The first has an {\tt XtNcellOffset}
of 0, the second 0.2, the third 0.4.  Obviously it is important that
they are drawn in the correct order for this to work.
\end{itemize}

There are two ways the AtPlotter can use to decide which order to draw
plots.  The first and default method, which is used when the AtPlotter
resource {\tt XtNrankChildren} is False, is to draw them in creation
order.  The first created child is drawn first, and so on.  The second
method, used when {\tt XtNrankChildren} is True, is to draw them
according to a programmer-specified rank order.  The parent widget
stores a constraint variable called {\tt XtNrank} of behalf of all its
children, and will use this to decide which order to draw in.   This
is more flexible but takes more programmer effort.  (When several
children have the same rank, they are drawn in unspecified order).

\subsection{Customizing Axis Layouts}

There are several alternatives to using the default calculated axis
bounds and tic positions.  The default behaviour (for the AtAxis
class) is to pick some number of tics (depending on axis length, the
font used to display labels, and the {\tt XtNticDensity} resource),
find a nice, round number for the tic interval that gives
approximately that number of tics, then round the endpoints up or down
to be a multiple of the tic interval.  Each tic is given a label by
doing a {\tt sprintf()} using the {\tt XtNticFormat} and {\tt
XtNticMultiplier} resources.  This is fine is the axis values are
numeric, but not very useful if the axis represents dates or
categories, or if you need to coordinate axes between separate graphs
(for example, having six variables to graph against a common X value,
each pair plotted on a separate graph, one graph on top of the other,
and all sharing the same X axis values --- which would look silly if
each X axis was in a different pixel position or had a different scale).

There are three separate mechanisms to address these problems.

\subsubsection{Label Axes}
The AtLabelAxis class is very useful if your axis doesn't represent
numbers.  There are two main areas this could be useful:
\begin{itemize}
\item
if you are doing something like a stacked bar graph, plotting a couple
of figures (say, quarterly sales) for each of several items (say,
state by state).  Labeling the X axis with numbers is silly.  Instead,
each X tic can be labeled with a string, i.e. ``Vic'', ``N.S.W.''
etc.  In this situation, you would want to a label and tic for  every
X axis value.

\item
If you are plotting values against dates, you would like to be able to
specify the axis tics as dates, not numbers.  Also, because dates are
not regular and months are not all the same length, automatically
deciding tic values cannot do the logical thing, such as putting a tic
at the start of every month.  You would also like to be able to choose
which X values have tics and hence labels.
\end{itemize}

The AtLabelAxis axis allows the application writer to specify arbitrary
labels to put on tics, and arbitrary positions to place tics, at the
expense of a bit more programming effort.  The programmer can specify
things like ``a tic on the first day of every second month'', and
label the axes with dates, which cannot be done algorithmically.

The plotter and axis code supports arbitrary X-Y plotting styles, but
as of this writing, all the implemented plot widgets assume the X
axis is integer valued, and that successive Y values are at successive
integral X values (i.e. there are no ``holes'' in the sequence of Y
values).  The AtLabelAxis also makes a similar assumption.  (This is
because the initial use of this widget set is to plot historical data
against date, and the AtLabelAxis is used for the X axis.  This will
cease to be a restriction in general once the XYPlot class is
implemented, although the AtLabelAxis and SPlot-derived classes will
still make those assumptions).

The application attaches data to the AtLabelAxis with a member
function called {\tt AtLabelAxisAttachData}\footnote{Which is {\em
not\/} an alias for the AtSPlot function!  This would be one place
where multiple inheritance would be nice, as the AtLabelAxis has
elements of both AxisCore and AtSPlot classes.} that acts similarly to the
attach procedures for the AtLinePlot and AtBarPlot classes.  It would be
used in a manner similar to this:
\begin{verbatim}
   AtLabelAxisAttachData(label_axis, (XtPointer) &answers[0].date_ptr, 
                          sizeof (answers[0]), 0, NUM_ANSWERS);
\end{verbatim}

The arguments to this function are:
\begin{itemize}
\item
The AtLabelAxis that you are attaching the data to.

\item
A pointer to a String that is the first X axis label.

\item
The stride, or number of bytes between successive Strings.

\item
The X axis value of the first String.  This may or may not be the
minimum value for the axis, depending on the {\tt XtNautoScale}
resource.

\item
The number of strings in the array.
\end{itemize}

If the {\it n\/}th String is non-{\tt NULL} and points to a non-empty
string, then a tic mark is placed at that X value with the label
specified by that string.  Otherwise no tic mark or label is placed
there.  This gives the application writer complete control over
labeling the axis.  (For example, in the above code fragment, the
application writer would make sure the {\tt date\_ptr} field of the
{\tt answers[]} array (which should be a {\tt char *}) would only be
set on elements representing the first of the month, and would point
to a string like ``July, 1990'').  The test program {\tt test.c} in
the source directory contains an example of this usage.

\subsubsection{Frame Axes}

The AtFrameAxis class is so named because the original use was to put
two more axes round simple graphs so that they were completely
enclosed.  (This gives a more balanced look.)  The frame axis is
conceptually attached to another AtAxisCore object (in this or another
graph), and, when asked about axis bounds or tic positions, gets the
answer by looking at the axis to which it is attached.  The frame axis
is attached to its target axis by setting the {\tt XtNwidget}
resource.

The only things imported from the target axis are the tic and subtic
values, the tic labels and the endpoints.  The resources concerned
with displaying the axis (e.g. things such as color, font, label, tic
length, whether or not to draw the tic labels, etc) are individually
settable.  This is very flexible (but may require two axes to be
changed instead of one in some circumstances).  

One use might be to have a frame axis as the X2 axis attached to the
normal X axis.  It would get the same tic, subtic and bounds
information as the X axis, giving a nice symmetric look.  The labels
would also be the same, even though they might be rendered in a
different font.

A second possibility in is in the six variables on three graphs
problem described above, where two of the three X axes would be frame
axes pointing at the X axis of the third graph.  This would ensure
that all X axes had the same scale, labels etc.

\subsubsection{Inter-graph linking}
\label{linking}
The third method for handling axes is the most flexible but also the
most complex for the programmer.  As part of the layout processing,
each axis gets presented with the minimum and maximum values of all of
the plot widgets that are associated with that axis.  The axis then
does whatever processing is required to determine the endpoints of
the axis (in user space, not pixels), such as rounding or examining
other axes.  Finally, before the values are returned to the main
plotter code, the Axiscore code calls the {\tt XtNrangeCallback} callback
of the axis.  This routine is passed three arguments: the widget ID of
the axis, the closure field specified when the callback was added
(using {\tt XtAddCallback()} or equivalent), and a pointer to an {\tt
AtAxisRangeArgs} structure.

The {\tt AtAxisRangeArgs} structure is defined in {\tt
<At/AxisCore.h>} and looks like this:
\begin{verbatim}
    typedef struct {
         double     *minp, *maxp, *tic_intervalp;
         int        *max_widthp; 
    } AtAxisRangeArgs;
\end{verbatim}

The four pointers point to the currently chosen values for the maximum
and minimum values of the axis, the interval (in user space) between
successive tics, and the maximum width (in pixels) of the tic labels.
The called routine can chose whatever it likes for these values and,
by setting the pointed-to variables, will affect the values used by
the axis.  

The number width field is supposed to be the width of the widest tic
label, and is used to calculate the axis ``width'' (and hence the
pixel position of the axis).  Like the axis ``width'' it represents
height of the labels for horizontal axes (as that is what determines
the pixel Y position for that axis), and the real width for vertical
axes (as that determines the X pixel position).  Why is this
important?  Consider the three stacked graphs discussed above.  The
pixel position of the Y axis of a graph depends on the width of the Y
axis.  So to maintain all Y axes at the same pixel locations is is
important to make all three Y axes have the same number width
(assuming all Y axes have the {\tt XtNdrawNumbers} and {\tt
XtNnumbersOutside} resources set to True), as well as making sure the
tic length and label resources etc. the same.

Another use for the XtNrangeCallback is shown in the test program.  To
make sure that both the Y and Y2 axis have the same length (in user
space) and pixel position, but with different minimum values, the
callback can save those values from one axis and force the
tic interval and maximum to the appropriate value on the other.  This
enables sensible comparisons between two elements that cover similar
range but are offset (say, Y values between 1500 and 1520 compared to
Y2 values between 1800 and 1820).

\subsection{Extending Graphs}

A facility that is important in the plot widgets implemented so far
is the ability to efficiently handle graphs that are being extended.
The intention is to allow efficient and reduced-flicker update of
graphs that are being added to in sort-of real time (say once every
few seconds).  As an example, consider something like xmeter or
perfmeter on the Sun --- a strip chart that is added to every 20
seconds, and, once every couple of minutes does a shift to the left to
leave more room to stuff to be added.  The AtSPlot class supports this
via a member function:\footnote{There are {\tt \#define}'d versions of
this for all subclasses of AtSPlot, including the AtLinePlot and AtBarPlot
classes.}
\begin{verbatim}
   AtSPlotDataExtended(widget, num);
\end{verbatim}

This tells the graph that extra data has arrived, and the new maximum
({\em not\/} the number added!) is now {\tt num}.  If there is enough
room on the X axis, and the new data doesn't go over the Y axis
bounds, the new data points are calculated and redrawn with minimum
effort, and little or no redrawing of the rest of the display.  If
either X or Y axis bounds are exceeded, or {\tt num} is less than the
current value, the equivalent of an attach is done and the graph is
redrawn.  The test program has a function called follow on the option
menu that demonstrates this.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{History}
\label{history}

This version of the plotter widget is significantly different to the
previous version (known as version 4).  Version 4 was worked on by
many people involved with M.I.T.'s Project Athena, and had grown to be
a fairly unmaintainable collection of fairly buggy features.  I
received the Version 4 code from MIT and was very impressed, but
needed to make a few changes (specifically, the multiple graph linking
and the date axis capability).  This turned out to be extremely
difficult, as the policy for various parts of the plotter was spread
around many modules and quite opaque.  Feeping Creaturism had long
since taken over the axis code and it was unmaintainable.  

One thing led to another, and I have ended up re-implementing much,
throwing out much, and adapting the rest.  The current package is the
result of my attempts to make something we needed in our
business-oriented environment.  It involves a complete redesign of the
interaction between the Plotter parent, the axes and the plot
children, as well as significant changes in the style of using within
applications.  

The re-implementation involved dropping a lot of the crud for various
reasons, mainly on the basis that it is easier to add it back later
(and properly designed and implemented) if someone screams.

As such, it comes under a couple of headings:
\begin{itemize}
\item
Some features were dropped because they were badly thought out, didn't
work, I couldn't understand what they were for or how they worked.
This includes the {\tt XtNforceSquare} and {\tt XtNforceAspect} resources,
the floating axis code, and all the selection mechanism and mouse
action routines.

\item
Some features haven't been converted to the current version, mainly
because I don't need them and haven't the resources to do the
conversion (this has already taken up WAY too much of my time --- just
ask my Boss!).  This included the Log axis code (which should go into
a subclass of AtAxis), the XYPlot, XYErrorPlot and Contourplot
classes (which would need a generalized version of the AtSPlot class to
subclass from, but the Plotter and Axis code should handle it all OK),

\item
Some things were taken more-or-less unchanged, with the exception of
being reformatted to be compilable with K\&R C compilers.  This
includes the AtFontFamily, and Scale code, and most of the
PostScript code.  These retain the original MIT copyright.

\item
Some things were modified to some small extent, either to fix bugs,
add features or make compatible with the rest of the code.  These
include the Text and AtTextPlot modules, as well as the AtPlot class.
They retain the MIT copyright.

\item
Some things were substantially modified, or re-written with constant
and detailed references to the original code and algorithms.  This
includes much of the Plotter and Axis code (most of which ended up in
the AtAxisCore class).  These retain the MIT copyright and have a BBY
copyright added.

\item
A fair quantity of stuff was written from the ground up by me.  This
comes with a BBY copyright that is the same as the MIT one (but with
the name changed!)  This includes the AtSPlot, AtLinePlot, AtBarPlot,
AtFrameAxis and AtLabelAxis classes, the test and sample programs, this
document, and much of the implementation and design of the Plotter and
AxisCore classes.

\end{itemize}

The file {\tt CHANGED-V4} in the source directory gives a list of what
has changed since Version 4, as an aid to porting.  Hint and tips for
this file gladly accepted.

\section{Sample Program Listing}
\label{sampleprog}
This is a listing of the {\tt sample\_prog.c} source file described in
Section \ref{walkthrough}.  It should be included in machine-readable
form with the source to the widget set.

\tgrindfile{sample_prog}
%
% Local Variables: %
% mode:latex %
% ispell-dictionary: "ispell-words" %
% End: %
\end{document}
