[Tex/LaTex] using macros in tikz/pgf

macrostikz-pgf

I am trying to plot a family of hyperbolas and don't want to repeat the function definition every time. So for example I have this:

\documentclass{article}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}[domain=-2:2]
        \draw plot ({exp(\x)+exp(-\x)}, {exp(\x)-exp(-\x)});
    \end{tikzpicture}
\end{document}

But now I want to put the point in a function:

\documentclass{article}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}[domain=-2:2]
        \def\hyper#1#2#3{({#1*exp(#3)+#2*exp(-#3)}, {#1*exp(#3)-#2*exp(-#3)})}
        \draw plot \hyper{1}{1}{\x};
    \end{tikzpicture}
\end{document}

But then I get

! Package tikz Error: Cannot parse this plotting
data.

I there an easy way to use such predefined macro as a point? Or is it not possible with plot?

I have seen Problem using macros to define tree substructures and Forcing tikz/pgf to expand macros within commands as well as pgf macro that returns a node and Programming in TikZ but I still don't understand what can be done when.

Any pointers to enlightening parts of the TikZ/PGF manual are also welcome.

Best Answer

\draw plot expects the x and y coordinates to be separated by a comma, but the way your function is set up now, it only sees one chunk of stuff (not correct LaTeX terminology).

One way to get around this is to put the \draw plot into the macro as well. You can make the macro accept an optional argument that is passed to the draw command, so you'll be able to alter the appearance of individual plots:

\documentclass{article}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}[domain=-2:2]
        \newcommand\hyper[4][]{\draw [#1] plot ({#2*exp(#4)+#3*exp(-#4)}, {#2*exp(#4)-#3*exp(-#4)})}
         \hyper[red]{1}{1}{\x};
         \hyper[blue]{0.5}{0.5}{\x};
    \end{tikzpicture}
\end{document}

Instead of using the \draw plot functionality, you may want to take a look at PGFPlots, which makes it easier to create plots and add axes and legends etc.

\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\newcommand\hyper[4][]{\addplot [#1] ({#2*exp(#4)+#3*exp(-#4)}, {#2*exp(#4)-#3*exp(-#4)});}
    \begin{tikzpicture}[domain=-2:2]
         \begin{axis}[xmin=0, xmax=4, smooth, axis lines=middle]
         \foreach \n in {0.25,0.5,...,2}{
            \hyper[domain=-1.5/\n:1.5/\n] {\n}{\n}{x}
         }
         \hyper[domain=-3:3, thick, red]{0.75}{0.75}{x}
         \end{axis}
    \end{tikzpicture}
\end{document}