Fix Extra \else in PGFPlots Slope Field – How to Handle Extra \else Error in TikZ PGFPlots

pgfplotstikz-pgf

I'm trying to plot a slope field of the function 2x/y using pgfplots such that the length of each quiver is fixed. The code is below

\documentclass{minimal}
\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}
    \begin{tikzpicture}
        \begin{axis}[
            declare function={
                f(\x,\y) = (\y != 0) * (2*\x/\y);
                length(\x,\y) = sqrt(1+(2*\x/\y)^2);
                result = (6 +0.5)/14;
            },
            domain=-0.5:6, 
            view={0}{90},
            axis lines=center
            ]
            \addplot3[blue, quiver={u={1/length(x,y)}, v={f(x,y)/length(x,y)}, scale arrows=result}, -stealth, samples=14] {0};
        \end{axis}
    \end{tikzpicture}% Extra \else. ...e arrows=result}, -stealth, samples=14] {0};
    
\end{document}

Here I define my functions and try to use them in the quiver plot. However, I get the following unhelpful error

! Extra \else.
\pgfmath@local@next ...@local@function@body \else
                                                  \if #1(\let \pgfmath@local...

l.32 ...e arrows=length}, -stealth, samples=14] {0};

I can't see what's wrong with the code. I have tried, without success

  • Changing the /= sign into other possible alternatives, such as !=,
  • Plugging in the function calls with their literals

Can I please have some help with this?

Best Answer

In your original code you had forgotten a ; at the end of the definition of result. That you get a Could not parse input 'result' as a floating point number, ... error indicates that the argument given to scale arrows isn't parsed as a number, so the function is interpreted. I don't whether this is a bug or by design. One possible workaround is to use \pgfmathsetmacro to parse result and save to a macro, as in the example below.

\documentclass{article} % don't use minimal https://tex.stackexchange.com/questions/42114
\usepackage{pgfplots} % loads tikz

\begin{document}
    \begin{tikzpicture}
        \begin{axis}[
            declare function={
                f(\x,\y) = (\y != 0) * (2*\x/\y);
                length(\x,\y) = sqrt(1+(2*\x/\y)^2);
                result = (6 +0.5)/14;
            },
            domain=-0.5:6, 
            view={0}{90},
            axis lines=center
            ]
            % make an intermediate macro for "result"
            \pgfmathsetmacro{\tmpres}{result}

            % and use \tmpres for "scale arrows"
            \addplot3[blue, quiver={u={1/length(x,y)}, v={f(x,y)/length(x,y)}, scale arrows=\tmpres}, -stealth, samples=14] {0};
        \end{axis}
    \end{tikzpicture}    
\end{document}

enter image description here