% Copyright 2007 by Till Tantau
%
% This file may be distributed and/or modified
%
% 1. under the LaTeX Project Public License and/or
% 2. under the GNU Free Documentation License.
%
% See the file doc/generic/pgf/licenses/LICENSE for more details.


\section{Plots of Functions}

\label{section-tikz-plots}

\subsection{When Should One Use \tikzname\ for Generating Plots? }

\label{section-why-pgname-for-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.

\emph{Note that is often not necessary to use \tikzname\ for plots.}
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.


\subsection{The Plot Path Operation}

The |plot| path operation can be used to append a line or curve to the path
that goes through a large number of coordinates. These coordinates are
either given in a simple list of coordinates, read from some file, or
they are computed on the fly.

The syntax of the |plot| comes in different versions.

\begin{pathoperation}{--plot}{\meta{further arguments}}
  This operation plots the curve through the coordinates specified in
  the \meta{further arguments}. The current (sub)path is simply
  continued, that is, a line-to operation to the first point of the
  curve is implicitly added. The details of the \meta{further
    arguments}  will be explained in a moment.
\end{pathoperation}

\begin{pathoperation}{plot}{\meta{further arguments}}
  This operation plots the curve through the coordinates specified in
  the \meta{further arguments} by first ``moving'' to the first
  coordinate of the curve.
\end{pathoperation}

The \meta{further arguments} are used in three different ways to
specifying the coordinates of the points to be plotted:

\begin{enumerate}
\item
  \opt{|--|}|plot|\oarg{local options}\declare{|coordinates{|\meta{coordinate
    1}\meta{coordinate 2}\dots\meta{coordinate $n$}|}|}
\item
  \opt{|--|}|plot|\oarg{local options}\declare{|file{|\meta{filename}|}|}
\item
  \opt{|--|}|plot|\oarg{local options}\declare{\meta{coordinate expression}}
\item
  \opt{|--|}|plot|\oarg{local options}\declare{|function{|\meta{gnuplot formula}|}|}
\end{enumerate}

These different ways are explained in the following.


\subsection{Plotting Points Given Inline}

In the first two cases, the points are given directly in the \TeX-file
as in the following example:

\begin{codeexample}[]
\tikz \draw plot coordinates {(0,0) (1,1) (2,0) (3,1) (2,1) (10:2cm)};
\end{codeexample}

Here is an example showing the difference between |plot| and |--plot|:

\begin{codeexample}[]
\begin{tikzpicture}
  \draw (0,0) -- (1,1) plot coordinates {(2,0)  (4,0)};
  \draw[color=red,xshift=5cm]
        (0,0) -- (1,1) -- plot coordinates {(2,0)  (4,0)};
\end{tikzpicture}
\end{codeexample}


\subsection{Plotting Points Read From an External File}

The second way of specifying points is to put them in an external
file named \meta{filename}. Currently, the only file format that
\tikzname\ allows is the following: Each line of the \meta{filename}
should contain one line starting with two numbers, separated by a
space. Anything following the two numbers on the line is
ignored. Also, lines starting with a |%| or a |#| are ignored as well
as empty lines. (This is exactly the format that \textsc{gnuplot}
produces when you say |set terminal table|.) If necessary, more
formats will be supported in the future, but it is usually easy to
produce a file containing data in this form.

\begin{codeexample}[]
\tikz \draw plot[mark=x,smooth] file {plots/pgfmanual-sine.table};
\end{codeexample}

The file |plots/pgfmanual-sine.table| reads:
\begin{codeexample}[code only]
#Curve 0, 20 points
#x y type
0.00000 0.00000  i
0.52632 0.50235  i
1.05263 0.86873  i
1.57895 0.99997  i
...
9.47368 -0.04889  i
10.00000 -0.54402  i
\end{codeexample}
It was produced from the following source, using |gnuplot|:
\begin{codeexample}[code only]
set terminal table
set output "../plots/pgfmanual-sine.table"
set format "%.5f"
set samples 20
plot [x=0:10] sin(x)
\end{codeexample}

The \meta{local options} of the |plot| operation are local to each
plot and do not affect other plots ``on the same path.'' For example,
|plot[yshift=1cm]| will locally shift the plot 1cm upward. Remember,
however, that most options can only be applied to paths as a
whole. For example, |plot[red]| does not have the effect of making the
plot red. After all, you are trying to ``locally'' make part of the
path red, which is not possible.

\subsection{Plotting a Function}
\label{section-tikz-plot}

When you plot a function, the coordinates of the plot data can be
computed by evaluating a mathematical expression. Since \pgfname\
comes with a mathematical engine, you can specify this expression and
then have \tikzname\ produce the desired coordinates for you,
automatically.

Since this case is quite common when plotting a function, the syntax
is easy: Following the |plot| command and its local options, you
directly provide a \meta{coordinate expression}. It looks like a
normal coordinate, but inside you may use a special macro, which is
|\x| by default, but this can be changed using the |variable|
option. The \meta{coordinate expression} is then evaluated for
different values for |\x| and the resulting coordinates are plotted.

Note that you will often have to put the $x$- or $y$-coordinate inside
braces, namely whenever you use an expression involving a paranthesis.

The following options influence how the \meta{coordinate expression}
is evaluated:
\begin{key}{/tikz/variable=\meta{macro} (initially x)}
  Sets the macro whose value is set to the different values when
  \meta{coordinate expression} is evaluated.
\end{key}

\begin{key}{/tikz/samples=\meta{number} (initially 25)}
  Sets the number of samples used in the plot.
\end{key}

\begin{key}{/tikz/domain=\meta{start}|:|\meta{end} (initially -5:5)}
  Sets the domain between which the samples are taken.
\end{key}

\begin{key}{/tikz/samples at=\meta{sample list}}
  This option specifies a list of positions for which the
  variable should be evaluated. For instance, you can say
  |samples at={1,2,8,9,10}| to have the variable evaluated exactly for
  values $1$, $2$, $8$, $9$, and $10$. You can use the |\foreach|
  syntax, so you can use |...| inside the \meta{sample list}.

  When this option is used, the |samples| and |domain| option are
  overruled. The other ways round, setting either |samples| or
  |domain| will overrule this option.
\end{key}

\begin{codeexample}[]
\begin{tikzpicture}[domain=0:4]
  \draw[very thin,color=gray] (-0.1,-1.1) grid (3.9,3.9);
  
  \draw[->] (-0.2,0) -- (4.2,0) node[right] {$x$};
  \draw[->] (0,-1.2) -- (0,4.2) node[above] {$f(x)$};
  
  \draw[color=red]    plot (\x,\x)             node[right] {$f(x) =x$};
  \draw[color=blue]   plot (\x,{sin(\x r)})    node[right] {$f(x) = \sin x$};
  \draw[color=orange] plot (\x,{0.05*exp(\x)}) node[right] {$f(x) = \frac{1}{20} \mathrm e^x$};
\end{tikzpicture}
\end{codeexample}

\begin{codeexample}[]
\tikz \draw[scale=0.5,domain=-3.141:3.141,smooth,variable=\t]
  plot ({\t*sin(\t r)},{\t*cos(\t r)});
\end{codeexample}

\begin{codeexample}[]
\tikz \draw[domain=0:360,smooth,variable=\t]
  plot ({sin(\t)},\t/360,{cos(\t)});
\end{codeexample}


\subsection{Plotting a Function Using Gnuplot}
\label{section-tikz-gnuplot}

Often, you will want to plot points that are given via a function like
$f(x) = x \sin x$. Unfortunately, \TeX\ does not really have enough
computational power to generate the points on such a function
efficiently (it is a text processing program, after all). However,
if you allow it, \TeX\ can try to call external programs that can
easily produce the necessary points. Currently, \tikzname\ knows how to
call \textsc{gnuplot}.

When \tikzname\ encounters your operation
|plot[id=|\meta{id}|] function{x*sin(x)}| for 
the first time, it will create a file called
\meta{prefix}\meta{id}|.gnuplot|, where \meta{prefix} is |\jobname.| by
default, that is, the name of you main |.tex| file. If no \meta{id} is
given, it will be empty, which is alright, but it is better when each
plot has a unique \meta{id} for reasons explained in a moment. Next,
\tikzname\ writes some initialization code into this file followed by
|plot x*sin(x)|. The initialization code sets up things 
such that the |plot| operation will write the coordinates into another
file called \meta{prefix}\meta{id}|.table|. Finally, this table file
is read as if you had said |plot file{|\meta{prefix}\meta{id}|.table}|. 

For the plotting mechanism to work, two conditions must be met:
\begin{enumerate}
\item
  You must have allowed \TeX\ to call external programs. This is often
  switched off by default since this is a security risk (you might,
  without knowing, run a \TeX\ file that calls all sorts of ``bad''
  commands). To enable this ``calling external programs'' a command
  line option must be given to the \TeX\ program. Usually, it is
  called something like |shell-escape| or |enable-write18|. For
  example, for my |pdflatex| the option |--shell-escape| can be
  given.
\item
  You must have installed the |gnuplot| program and \TeX\ must find it
  when compiling your file.
\end{enumerate}

Unfortunately, these conditions will not always be met. Especially if
you pass some source to a coauthor and the coauthor does not have
\textsc{gnuplot} installed, he or she will have trouble compiling your
files.

For this reason, \tikzname\ behaves differently when you compile your
graphic for the second time: If upon reaching
|plot[id=|\meta{id}|] function{...}| the file \meta{prefix}\meta{id}|.table|
already exists \emph{and} if the \meta{prefix}\meta{id}|.gnuplot| file
contains what \tikzname\ thinks that it ``should'' contain, the |.table|
file is immediately read without trying to call a |gnuplot|
program. This approach has the following advantages: 
\begin{enumerate}
\item
  If you pass a bundle of your |.tex| file and all |.gnuplot| and
  |.table| files to someone else, that person can \TeX\ the |.tex|
  file without having to have |gnuplot| installed.
\item
  If the |\write18| feature is switched off for security reasons (a
  good idea), then, upon the first compilation of the |.tex| file, the
  |.gnuplot| will still be generated, but not the |.table|
  file. You can then simply call |gnuplot| ``by hand'' for each
  |.gnuplot| file, which will produce all necessary |.table| files.
\item
  If you change the function that you wish to plot or its
  domain, \tikzname\ will automatically try to regenerate the |.table|
  file.
\item
  If, out of laziness, you do not provide an |id|, the same |.gnuplot|
  will be used for different plots, but this is not a problem since
  the |.table| will automatically be regenerated for each plot
  on-the-fly. \emph{Note: If you intend to share your files with
  someone else, always use an id, so that the file can by typeset
  without having \textsc{gnuplot} installed.} Also, having unique ids
  for each plot will improve compilation speed since no external
  programs need to be called, unless it is really necessary.
\end{enumerate}

When you use |plot function{|\meta{gnuplot formula}|}|, the \meta{gnuplot
  formula} must be given in the |gnuplot| syntax, whose details are
beyond the scope of this manual. Here is the ultra-condensed
essence: Use |x| as the variable and use the C-syntax for normal
plots, use |t| as the variable for parametric plots. Here are some examples:

\begin{codeexample}[]
\begin{tikzpicture}[domain=0:4]
  \draw[very thin,color=gray] (-0.1,-1.1) grid (3.9,3.9);
  
  \draw[->] (-0.2,0) -- (4.2,0) node[right] {$x$};
  \draw[->] (0,-1.2) -- (0,4.2) node[above] {$f(x)$};
  
  \draw[color=red]    plot[id=x]   function{x}           node[right] {$f(x) =x$};
  \draw[color=blue]   plot[id=sin] function{sin(x)}      node[right] {$f(x) = \sin x$};
  \draw[color=orange] plot[id=exp] function{0.05*exp(x)} node[right] {$f(x) = \frac{1}{20} \mathrm e^x$};
\end{tikzpicture}
\end{codeexample}


The plot in influenced by the following options: First, the options
|samples| and |domain| explained earlier. Second, there are some more
specialized options.

\begin{key}{/tikz/parametric=\meta{boolena} (default true)}
  Sets whether the plot is a parametric plot. If true, then |t| must
  be used instead of |x| as the parameter and two comma-separated
  functions must be given in the \meta{gnuplot formula}. An example is
  the following:
\begin{codeexample}[]
\tikz \draw[scale=0.5,domain=-3.141:3.141,smooth]
  plot[parametric,id=parametric-example] function{t*sin(t),t*cos(t)};
\end{codeexample}
\end{key}

\begin{key}{/tikz/id=\meta{id}}
  Sets the identifier of the current plot. This should be a unique
  identifier for each plot (though things will also work if it is not,
  but not as well, see the explanations above). The \meta{id} will be
  part of a filename, so it should not contain anything fancy like |*|
  or |$|.%$
\end{key}

\begin{key}{/tikz/prefix=\meta{prefix}}
  The \meta{prefix} is put before each plot file name. The default is
  |\jobname.|, but 
  if you have many plots, it might be better to use, say |plots/| and
  have all plots placed in a directory. You have to create the
  directory yourself.
\end{key}

\begin{key}{/tikz/raw gnuplot}
  This key causes the \meta{gnuplot formula} to be passed on to
  \textsc{gnuplot} without setting up the samples or the |plot|
  operation. Thus, you could write
\begin{codeexample}[code only]
plot[raw gnuplot,id=raw-example] function{set samples 25; plot sin(x)}
\end{codeexample}
  This can be 
  useful for complicated things that need to be passed to
  \textsc{gnuplot}. However, for really complicated situations you
  should create a special external generating \textsc{gnuplot} file
  and use the |file|-syntax to include the table ``by hand.''
\end{key}

The following styles influence the plot:
\begin{stylekey}{/tikz/every plot (initially \normalfont empyt)}
  This style is installed in each plot, that is, as if you always said
\begin{codeexample}[code only]
  plot[every plot,...]
\end{codeexample}
 This is most useful for globally setting a prefix for all plots by saying:
\begin{codeexample}[code only]
\tikzset{every plot/.style={prefix=plots/}}
\end{codeexample}
\end{stylekey}



\subsection{Placing Marks on the Plot}

As we saw already, it is possible to add \emph{marks} to a plot using
the |mark| option. When this option is used, a copy of the plot
mark is placed on each point of the plot. Note that the marks are
placed \emph{after} the whole path has been drawn/filled/shaded. In
this respect, they are handled like text nodes. 

In detail, the following options govern how marks are drawn:
\begin{key}{/tikz/mark=\meta{mark mnemonic}}
  Sets the mark to a mnemonic that has previously been defined using
  the |\pgfdeclareplotmark|. By default, |*|, |+|, and |x| are available,
  which draw a filled circle, a plus, and a cross as marks. Many more
  marks become available when the library |pgflibraryplotmarks| is
  loaded. Section~\ref{section-plot-marks} lists the available plot
  marks.

  One plot mark is special: the |ball| plot mark is available only
  it \tikzname. The |ball color| determines the balls's color. Do not use
  this option with a large number of marks since it will take very long
  to render in PostScript.
  
  \begin{tabular}{lc}
    Option & Effect \\\hline \vrule height14pt width0pt
    \plotmarkentrytikz{ball}
  \end{tabular}
\end{key}

\begin{key}{/tikz/mark repeat=\meta{r}}
  This option tells \tikzname\ that only every $r$th mark should be
  drawn.
  
\begin{codeexample}[]
\tikz \draw plot[mark=x,mark repeat=3,smooth] file {plots/pgfmanual-sine.table};
\end{codeexample}
\end{key}

\begin{key}{/tikz/mark phase=\meta{p}}
  This option tells \tikzname\ that the first mark to be draw should
  be the $p$th, followed by the $(p+r)$th, then the $(p+2r)$th, and so
  on.
  
\begin{codeexample}[]
\tikz \draw plot[mark=x,mark repeat=3,mark phase=6,smooth] file {plots/pgfmanual-sine.table};
\end{codeexample}
\end{key}

\begin{key}{/tikz/mark indices=\meta{list}}
  This option allows you to specify explicitly the indices at which a
  mark should be placed. Counting starts with 1. You can use the
  |\foreach| syntax, that is, |...| can be used.
    
\begin{codeexample}[]
\tikz \draw plot[mark=x,mark indices={1,4,...,10,11,12,...,16,20},smooth]
  file {plots/pgfmanual-sine.table};
\end{codeexample}
\end{key}

\begin{key}{/tikz/mark size=\meta{dimension}}
  Sets the size of the plot marks. For circular plot marks,
  \meta{dimension} is the radius, for other plot marks
  \meta{dimension} should be about half the width and height.

  This option is not really necessary, since you achieve the same
  effect by specifying |scale=|\meta{factor} as a local option, where
  \meta{factor} is the quotient of the desired size and the default
  size. However, using |mark size| is a bit faster and more natural. 
\end{key}

\begin{key}{/tikz/mark options=\meta{options}}
  These options are applied to marks when they are drawn. For example,
  you can scale (or otherwise transform) the plot mark or set its
  color. 
\begin{codeexample}[]
\tikz \fill[fill=blue!20]
  plot[mark=triangle*,mark options={color=blue,rotate=180}]
    file{plots/pgfmanual-sine.table} |- (0,0);
\end{codeexample}
\end{key}



\subsection{Smooth Plots, Sharp Plots, and Comb Plots}

There are different things the |plot| operation can do with the points
it reads from a file or from the inlined list of points. By default,
it will connect these points by straight lines. However, you can also
use options to change the behavior of |plot|.

\begin{key}{/tikz/sharp plot}
  This is the default and causes the points to be connected by
  straight lines. This option is included only so that you can
  ``switch back'' if you ``globally'' install, say, |smooth|.
\end{key}

\begin{key}{/tikz/smooth}
  This option causes the points on the path to be connected using a
  smooth curve:

\begin{codeexample}[]
\tikz\draw plot[smooth] file{plots/pgfmanual-sine.table};
\end{codeexample}

  Note that the smoothing algorithm is not very intelligent. You will
  get the best results if the bending angles are small, that is, less
  than about $30^\circ$ and, even more importantly, if the distances
  between points are about the same all over the plotting path.
\end{key}

\begin{key}{/tikz/tension=\meta{value}}
  This option influences how ``tight'' the smoothing is. A lower value
  will result in sharper corners, a higher value in more ``round''
  curves. A value of $1$ results in a circle if four points at
  quarter-positions on a circle are given. The default is $0.55$. The
  ``correct'' value depends on the details of plot.
  
\begin{codeexample}[]
\begin{tikzpicture}[smooth cycle]
  \draw                 plot[tension=0.2]
    coordinates{(0,0) (1,1) (2,0) (1,-1)};
  \draw[yshift=-2.25cm] plot[tension=0.5]
    coordinates{(0,0) (1,1) (2,0) (1,-1)};
  \draw[yshift=-4.5cm]  plot[tension=1]
    coordinates{(0,0) (1,1) (2,0) (1,-1)};
\end{tikzpicture}
\end{codeexample}
\end{key}

\begin{key}{/tikz/smooth cycle}
  This option causes the points on the path to be connected using a
  closed smooth curve. 

\begin{codeexample}[]
\tikz[scale=0.5]
  \draw plot[smooth cycle] coordinates{(0,0) (1,0) (2,1) (1,2)}
        plot               coordinates{(0,0) (1,0) (2,1) (1,2)} -- cycle;
\end{codeexample}
\end{key}

\begin{key}{/tikz/ycomb}
  This option causes the |plot| operation to interpret the plotting
  points differently. Instead of connecting them, for each point of
  the plot a straight line is added to the path from the $x$-axis to the point,
  resulting in a sort of ``comb'' or ``bar diagram.''

\begin{codeexample}[]
\tikz\draw[ultra thick] plot[ycomb,thin,mark=*] file{plots/pgfmanual-sine.table};
\end{codeexample}

\begin{codeexample}[]
\begin{tikzpicture}[ycomb]
  \draw[color=red,line width=6pt]
    plot coordinates{(0,1) (.5,1.2) (1,.6) (1.5,.7) (2,.9)};
  \draw[color=red!50,line width=4pt,xshift=3pt]
    plot coordinates{(0,1.2) (.5,1.3) (1,.5) (1.5,.2) (2,.5)};
\end{tikzpicture}
\end{codeexample}
\end{key}


\begin{key}{/tikz/xcomb}
  This option works like |ycomb| except that the bars are horizontal. 

\begin{codeexample}[]
\tikz \draw plot[xcomb,mark=x] coordinates{(1,0) (0.8,0.2) (0.6,0.4) (0.2,1)};
\end{codeexample}
\end{key}


\begin{key}{/tikz/polar comb}
  This option causes a line from the origin to the point to be added
  to the path for each plot point.

\begin{codeexample}[]
\tikz \draw plot[polar comb,
     mark=pentagon*,mark options={fill=white,draw=red},mark size=4pt]
   coordinates {(0:1cm) (30:1.5cm) (160:.5cm) (250:2cm) (-60:.8cm)};
\end{codeexample}
\end{key}


\begin{key}{/tikz/only marks}
  This option causes only marks to be shown; no path segments are
  added to the actual path. This can be useful for quickly adding some
  marks to a path.

\begin{codeexample}[]
\tikz \draw (0,0) sin (1,1) cos (2,0)
  plot[only marks,mark=x] coordinates{(0,0) (1,1) (2,0) (3,-1)};
\end{codeexample}
\end{key}

