1

I would like to be able to "globally" declare a function for use in PGFplots. That is, I want to be able to declare a function a single time, and be able to use it without having to declare it on every single plot.

Here is an MWE for what I am doing now:

\documentclass{article}

\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}[declare function = {func(\x) = \x^2;}]
\begin{axis}
\addplot[domain=0:1] {func(x)};
\end{axis}
\end{tikzpicture}

\vspace{1em}

\begin{tikzpicture}[declare function = {func(\x) = \x^2;}]
\begin{axis}
\addplot[domain=0:1] {func(x)};
\end{axis}
\end{tikzpicture}
\end{document}

Essentially the goal would be to have something like

declare global function = {func{\x} = \x^2;}

somewhere in the header and then be able to use func throughout. Is there any way to do this?

Note: I specifically want to do this in PGFplots so stuff in "raw" tikz is not going to be so helpful to me.

  • 1
    Be aware that \x^2 might not behave as you'd expect. For example when \x is -2 then \x^2 becomes -2^2 which is -4. If you want to have a parabola, you would have to use (\x)^2 instead. – Henri Menke May 11 '19 at 03:10
  • Or x*x, which is also much faster. – John Kormylo May 11 '19 at 04:21
  • Further reading on these issues: https://tex.stackexchange.com/a/125896/121799. –  May 11 '19 at 04:31

1 Answers1

4

Very simple: add \tikzset{declare function = {func(\x) = \x^2;}} somewhere (not inside a group).

\documentclass{article}

\usepackage{tikz}
\usepackage{pgfplots}
\tikzset{declare function = {func(\x) = \x^2;}}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot[domain=0:1] {func(x)};
\end{axis}
\end{tikzpicture}

\vspace{1em}

\begin{tikzpicture}
\begin{axis}
\addplot[domain=0:1] {func(x)};
\end{axis}
\end{tikzpicture}
\end{document}

enter image description here

However, I advise not to do that unless you are absolutely sure you want to assign this name to the function ``forever and always''.

The reason is that the inverse process is much harder. To see this, consider

\documentclass{article}

\usepackage{tikz}
\usepackage{pgfplots}
\tikzset{declare function = {func(\x) = \x^2;}}
\begin{document}
\begin{tikzpicture}
\begin{axis}
\addplot[domain=0:1] {func(x)};
\end{axis}
\end{tikzpicture}

\vspace{1em}

\begin{tikzpicture}[declare function = {func(\x) = \x^2;}]
\begin{axis}
\addplot[domain=0:1] {func(x)};
\end{axis}
\end{tikzpicture}
\end{document}

which throws the error

! Package PGF Math Error: The function `func' already exists.

That is, unlike ordinary pgf keys, you can not simply locally overwrite the function using the declare function key. For that reason I would recommend to keep the function definitons local, or, if you absolutely have to, give them very unique names. Of course, there is the command \pgfmathdeclarefunction* that allows you to overwrite definitions that you made and want to revise, see section 95 Customizing the Mathematical Engine for more details.