% Copyright 2003 by Till Tantau <tantau@cs.tu-berlin.de>.
%
% This program can be redistributed and/or modified under the terms
% of the LaTeX Project Public License Distributed from CTAN
% archives in directory macros/latex/base/lppl.txt.


\section{Creating Plots}

\label{section-plots}

This section describes the |pgfbaseplot| package.

\begin{package}{pgfbaseplot}
  This package provides a set of commands that are intended to make it
  reasonably easy to plot functions using \pgfname. It is loaded
  automatically by |pgf|, but you can load it manually if you have
  only included |pgfcore|.  
\end{package}

\subsection{Overview}

\subsubsection{When Should One Use PGF for Generating Plots? }

There exist many powerful programs that produce plots, examples are
\textsc{gnuplot} or \textsc{mathematica}. These programs can produce
two different kinds of output: First, they can output a complete plot
picture in a certain format (like \pdf) that includes all low-level
commands necessary for drawing the complete plot (including axes and
labels). Second, they can usually also produce ``just plain data'' in
the form of a long list of coordinates. Most of the powerful programs
consider it a to be ``a bit boring'' to just output tabled data and
very much prefer to produce fancy pictures. Nevertheless, when coaxed,
they can also provide the plain data.

The plotting mechanism described in the following deals only with
plotting data given in the form of a list of coordinates. Thus, this
section is about using \pgfname\ to turn lists of coordinates into
plots.

\emph{Note that is often not necessary to use \pgfname\ for this.}
Programs like \textsc{gnuplot} can produce very sophisticated plots
and it is usually much easier to simply include these plots as a
finished \textsc{pdf} or PostScript graphics.

However, there are a number of reasons why you may wish to invest time
and energy into mastering the \pgfname\ commands for creating plots:

\begin{itemize}
\item
  Virtually all plots produced by ``external programs'' use different
  fonts from the one used in your document.
\item
  Even worse, formulas will look totally different, if they can be
  rendered at all.
\item
  Line width will usually be too large or too small.
\item
  Scaling effects upon inclusion can create a mismatch between sizes
  in the plot and sizes in the text.
\item
  The automatic grid generated by most programs is mostly
  distracting. 
\item
  The automatic ticks generated by most programs are cryptic
  numerics. (Try adding a tick reading ``$\pi$'' at the right point.)
\item
  Most programs make it very easy to create ``chart junk'' in a most
  convenient fashion.  All show, no content.
\item
  Arrows and plot marks will almost never match the arrows used in the
  rest of the document.
\end{itemize}

The above list is not exhaustive, unfortunately.


\subsubsection{How PGF Handles Plots}

\pgfname\ (conceptually) uses a two-stage process for generating
plots. First, a \emph{plot stream} must be produced. This stream
consists (more or less) of a large number of coordinates. Second a 
\emph{plot handler} is applied to the stream. A plot handler ``does
something'' with the stream. The standard handler will issue
line-to operations to the coordinates in the stream. However, a
handler might also try to issue appropriate curve-to operations in
order to smooth the curve. A handler may even do something else
entirely, like writing each coordinate to another stream, thereby
duplicating the original stream.

Both for the creation of streams and the handling of streams different
sets of commands exist. The commands for creating streams start with
|\pgfplotstream|, the commands for setting the handler start with
|\pgfplothandler|.



\subsection{Generating Plot Streams}

\subsubsection{Basic Building Blocks of Plot Streams}
A \emph{plot stream} is a (long) sequence of the following three
commands:
\begin{enumerate}
\item
  |\pgfplotstreamstart|,
\item
  |\pgfplotstreampoint|, and
\item
  |\pgfplotstreamend|.
\end{enumerate}
Between calls of these commands arbitrary other code may be
called. Obviously, the stream should start with the first command and
end with the last command. Here is an example of a plot stream:
\begin{codeexample}[code only]
\pgfplotstreamstart
\pgfplotstreampoint{\pgfpoint{1cm}{1cm}}
\newdimen\mydim
\mydim=2cm
\pgfplotstreampoint{\pgfpoint{\mydim}{2cm}}
\advance \mydim by 3cm
\pgfplotstreampoint{\pgfpoint{\mydim}{2cm}}
\pgfplotstreamend
\end{codeexample}

\begin{command}{\pgfplotstreamstart}
  This command signals that a plot stream starts. The effect of this
  command is to call the internal command |\pgf@plotstreamstart|,
  which is set by the current plot handler to do whatever needs to be
  done at the beginning of the plot.
\end{command}

\begin{command}{\pgfplotstreampoint\marg{point}}
  This command adds a \meta{point} to the current plot stream. The
  effect of this command is to call the internal command |\pgf@plotstreampoint|,
  which is also set by the current plot handler. This command should
  now ``handle'' the point in some sensible way. For example, a
  line-to command might be issued for the point.
\end{command}

\begin{command}{\pgfplotstreamend}
  This command signals that a plot stream ends. It calls
  |\pgf@plotstreamend|, which should now do any necessary ``cleanup.''
\end{command}

Note that plot streams are not buffered, that is, the different points
are handled immediately. However, using the recording handler, it is
possible to record a stream.

\subsubsection{Commands That Generate Plot Streams}

Plot streams can be created ``by hand'' as in the earlier
example. However, most of the time the coordinates will be produced
internally by some command. For example, the |\pgfplotxyfile| reads a
file and converts it into a plot stream.

\begin{command}{\pgfplotxyfile\marg{filename}}
  This command will try to open the file \meta{filename}. If this
  succeeds, it will convert the file contents into a plot stream as
  follows: A |\pgfplotstreamstart| is issued. Then, each nonempty line
  of the file should start with two numbers separated by a space, such
  as |0.1 1| or |100 -.3|. Anything following the numbers is ignored.

  Each pair \meta{x} and \meta{y} of numbers is converted into one
  plot stream point in the xy-coordinate system. Thus, a line like
\begin{codeexample}[code only]
2 -5 some text
\end{codeexample}
  is turned into 
\begin{codeexample}[code only]
\pgfplotstreampoint{\pgfpointxy{2}{-5}}
\end{codeexample}

  The two characters |%| and |#| are also allowed in a file and they
  are both treated as comment characters. Thus, a line starting with
  either of them is empty and, hence, ignored.

  When the file has been read completely, |\pgfplotstreamend| is
  called. 
\end{command}


\begin{command}{\pgfplotxyzfile\marg{filename}}
  This command works like |\pgfplotxyfile|, only \emph{three} numbers
  are expected on each non-empty line. They are converted into points
  in the xyz-coordinate system. Consider, the following file:
\begin{codeexample}[code only]
% Some comments
# more comments
2 -5  1 first entry
2 -.2 2 second entry
2 -5  2 third entry
\end{codeexample}
  It is turned into the following stream:
\begin{codeexample}[code only]
\pgfplotstreamstart
\pgfplotstreampoint{\pgfpointxyz{2}{-5}{1}}
\pgfplotstreampoint{\pgfpointxyz{2}{-.2}{2}}
\pgfplotstreampoint{\pgfpointxyz{2}{-5}{2}}
\pgfplotstreamend
\end{codeexample}
\end{command}


Currently, there is no command that can decide automatically whether
the xy-coordinate system should be used or whether the xyz-system
should be used. However, it would not be terribly difficult to write a
``smart file reader'' that parses coordinate files a bit more
intelligently. 


\begin{command}{\pgfplotgnuplot\oarg{prefix}\marg{function}}
  This command will ``try'' to call the \textsc{gnuplot} program to
  generate the coordinates of the \meta{function}. In detail, the
  following happens:

  This command works with two files: \meta{prefix}|.gnuplot| and
  \meta{prefix}|.table|.  If the optional argument \meta{prefix} is
  not given, it is set to |\jobname|.

  Let us start with the situation where none of these files
  exists. Then \pgfname\ will first generate the file
  \meta{prefix}|.gnuplot|. In this file it writes
\begin{codeexample}[code only]
set terminal table; set output "#1.table"; set format "%.5f"
\end{codeexample}
  where |#1| is replaced by \meta{prefix}. Then, in a second line, it
  writes the text \meta{function}.

  Next, \pgfname\ will try to invoke the program |gnuplot| with the
  argument \meta{prefix}|.gnuplot|. This call may or may not succeed,
  depending on whether the |\write18| mechanism (also known as
  shell escape) is switched on and whether the |gnuplot| program is
  available.

  Assuming that the call succeeded, the next step is to invoke
  |\pgfplotxyfile| on the file \meta{prefix}|.table|; which is exactly
  the file that has just been created by |gnuplot|.
  
\begin{codeexample}[]
\begin{tikzpicture}
  \draw[help lines] (0,-1) grid (4,1);
  \pgfplothandlerlineto
  \pgfplotgnuplot[plots/pgfplotgnuplot-example]{plot [x=0:3.5] x*sin(x)}
  \pgfusepath{stroke}
\end{tikzpicture}
\end{codeexample}

  The more difficult situation arises when the |.gnuplot| file exists,
  which will be the case on the second run of \TeX\ on the \TeX\
  file. In this case \pgfname\ will read this file and check whether
  it contains exactly what \pgfname\ ``would have written'' into
  this file. If this is not the case, the file contents is overwritten
  with what ``should be there'' and, as above, |gnuplot| is invoked to
  generate a new |.table| file. However, if the file contents is ``as
  expected,'' the external |gnuplot| program is \emph{not}
  called. Instead, the \meta{prefix}|.table| file is immediately
  read.

  As explained in Section~\ref{section-tikz-gnuplot}, the net effect
  of the above mechanism is that |gnuplot| is called as little as
  possible and that when you pass along the |.gnuplot| and |.table|
  files with your |.tex| file to someone else, that person can
  \TeX\ the |.tex| file without having |gnuplot| installed and without
  having the |\write18| mechanism switched on.
\end{command}



\subsection{Plot Handlers}

\label{section-plot-handlers}

A \emph{plot handler}  prescribes what ``should be done'' with a
plot stream. You must set the plot handler before the stream starts.
The following commands install the most basic plot handlers; more plot
handlers are defined in the file |pgflibraryplothandlers|, which is
documented in Section~\ref{section-library-plothandlers}.

All plot handlers work by setting redefining the following three
macros: |\pgf@plotstreamstart|, |\pgf@plotstreampoint|, and
|\pgf@plotstreamend|.

\begin{command}{\pgfplothandlerlineto}
  This handler will issue a |\pgfpathlineto| command for each point of
  the plot, \emph{except} possibly for the first. What happens with
  the first point can be specified using the two commands described
  below.

\begin{codeexample}[]
\begin{pgfpicture}
  \pgfpathmoveto{\pgfpointorigin}
  \pgfplothandlerlineto
  \pgfplotstreamstart
  \pgfplotstreampoint{\pgfpoint{1cm}{0cm}}
  \pgfplotstreampoint{\pgfpoint{2cm}{1cm}}
  \pgfplotstreampoint{\pgfpoint{3cm}{2cm}}
  \pgfplotstreampoint{\pgfpoint{1cm}{2cm}}
  \pgfplotstreamend
  \pgfusepath{stroke}
\end{pgfpicture}
\end{codeexample}
\end{command}

\begin{command}{\pgfsetmovetofirstplotpoint}
  Specifies that the line-to plot handler (and also some other plot 
  handlers) should issue a move-to command for the
  first point of the plot instead of a line-to. This will start a new
  part of the current path, which is not always, but often,
  desirable. This is the default.
\end{command}

\begin{command}{\pgfsetlinetofirstplotpoint}
  Specifies that  plot handlers should issue a line-to command for the
  first point of the plot.

\begin{codeexample}[]
\begin{pgfpicture}
  \pgfpathmoveto{\pgfpointorigin}
  \pgfsetlinetofirstplotpoint
  \pgfplothandlerlineto
  \pgfplotstreamstart
  \pgfplotstreampoint{\pgfpoint{1cm}{0cm}}
  \pgfplotstreampoint{\pgfpoint{2cm}{1cm}}
  \pgfplotstreampoint{\pgfpoint{3cm}{2cm}}
  \pgfplotstreampoint{\pgfpoint{1cm}{2cm}}
  \pgfplotstreamend
  \pgfusepath{stroke}
\end{pgfpicture}
\end{codeexample}
\end{command}

\begin{command}{\pgfplothandlerdiscard}
  This handler will simply throw away the stream.
\end{command}

\begin{command}{\pgfplothandlerrecord\marg{macro}}
  When this handler is installed, each time a plot stream command is
  called, this command will be appended to \meta{macros}. Thus, at
  the end of the stream, \meta{macro} will contain all the
  commands that were issued on the stream. You can then install
  another handler and invoke \meta{macro} to ``replay'' the stream
  (possibly many times).
 
\begin{codeexample}[]
\begin{pgfpicture}
  \pgfplothandlerrecord{\mystream}
  \pgfplotstreamstart
  \pgfplotstreampoint{\pgfpoint{1cm}{0cm}}
  \pgfplotstreampoint{\pgfpoint{2cm}{1cm}}
  \pgfplotstreampoint{\pgfpoint{3cm}{1cm}}
  \pgfplotstreampoint{\pgfpoint{1cm}{2cm}}
  \pgfplotstreamend
  \pgfplothandlerlineto
  \mystream
  \pgfplothandlerclosedcurve
  \mystream
  \pgfusepath{stroke}
\end{pgfpicture}
\end{codeexample} 
\end{command}

%%% Local Variables: 
%%% mode: latex
%%% TeX-master: "pgfmanual"
%%% End: 
