How to Define a Function Once in PGFPlots
At a glance
- 1. Declare the function
Use PGF's math-function declaration to give the function one reusable definition.
- 2. Compute a value
Call the function inside pgfmathsetmacro or another PGF math expression.
- 3. Plot the same function
Use the declared function in an ordinary PGFPlots addplot expression.
- 4. Check the backend
A gnuplot expression uses a different language and cannot directly call a PGF math function.
To compute with a function and plot it in PGFPlots, define it once as a PGF math function. You can then call that function in calculations such as \pgfmathsetmacro and in a regular \addplot expression.
This works when PGFPlots evaluates the expression itself. If you use its gnuplot backend, the formula is evaluated by gnuplot instead, and the two systems do not automatically share function definitions.
Define a function for PGF math
Use \pgfmathdeclarefunction to declare a function and specify how many arguments it takes. The following example defines a one-argument function:
\pgfmathdeclarefunction{myfun}{1}{%
\pgfmathparse{(#1)^2 + 2*(#1) + 1}%
}
The first argument is the function name, the second is the number of arguments, and the final argument is the code that calculates the result. Here, #1 stands for the input value. The function is
Once declared, use the same name wherever PGF’s math parser accepts a function. For example, \pgfmathsetmacro{\myfunvalue}{myfun(3)} computes its value at 3. In a PGFPlots axis, \addplot {myfun(x)}; draws its graph.
Complete example
This document calculates the function at and plots the same function over the interval :
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\pgfmathdeclarefunction{myfun}{1}{%
\pgfmathparse{(#1)^2 + 2*(#1) + 1}%
}
\begin{document}
\pgfmathsetmacro{\myfunvalue}{myfun(3)}
The value at $x=3$ is \pgfmathprintnumber{\myfunvalue}.
\begin{tikzpicture}
\begin{axis}[
domain=-2:2,
samples=101,
xlabel={$x$},
ylabel={$myfun(x)$},
grid=major,
]
\addplot[blue, thick] {myfun(x)};
\end{axis}
\end{tikzpicture}
\end{document}
The calculation gives , so the document prints 16. The plot uses the same declaration; there is no second copy of the formula to update if the function changes. The code requires the pgfplots package, which loads TikZ.
Using a gnuplot plot
A declaration made with \pgfmathdeclarefunction belongs to PGF’s math parser. Gnuplot has its own syntax and evaluates its own expressions, so this will not make myfun available inside a gnuplot command.
For example, a gnuplot plot can define the function in its own script:
\addplot gnuplot [raw gnuplot] {
myfun(x) = x**2 + 2*x + 1;
plot [x=-2:2] myfun(x);
};
Running this example requires an installed gnuplot executable and shell-escape-enabled compilation, since PGFPlots runs gnuplot externally.
That definition is in gnuplot, not PGF math. If you also calculate values using PGF, you would need a separate PGF definition, which means maintaining the formula twice. To avoid that duplication, use ordinary \addplot {myfun(x)} for expressions PGF can handle. If you need gnuplot’s extra capabilities, choose one authoritative place for the formula and generate or transfer the other representation deliberately.
Common mistakes
- Defining a TeX macro instead of a math function. A command created with
\newcommandis not necessarily understood as a function by PGF’s math parser. Use\pgfmathdeclarefunctionfor expressions passed to PGF math and\addplot. - Calling a PGF function from gnuplot. The gnuplot backend does not evaluate a PGF declaration. Define the function in gnuplot syntax if the plot is evaluated there.
- Copying the formula into several places. Duplicate definitions can become inconsistent. Keep one definition for PGF calculations and PGFPlots plots, or clearly treat the PGF and gnuplot definitions as separate implementations.
- Using a function that exceeds PGF math’s needs. PGF math is convenient for many ordinary formulas, but it has numerical and feature limitations compared with a dedicated computation environment. For calculations requiring greater precision or unsupported operations, calculate externally and plot data, or use a suitable backend.
References
Spotted an error? Send a correction. Read how we write and check articles in our editorial policy.