2

When I plot conditional functions with a domain gap in it the plot starts at the wrong point for the second range. It's easier when just looking at it:

enter image description here

The function definition for red should just print the upper part. I have no idea why it always starts at the base level where the first domain ended.

Does anybody know where this behavior comes from, why it doesn't happen with smaller numbers like shown with the green function and possibly how to fix it?

Code for the above example:

\documentclass[]{scrreprt}
\usepackage{pgfplots}
\begin{document}

\tikzset{declare function={
        correct(\x)= (\x<=250000) * (100) + 
         and(\x>250000, \x<=500000) * (100 + \x / 1000);
    }
}
\tikzset{declare function={
        notCorrect(\x)= (\x<=1000000) * (0) + 
         and(\x>1000000, \x<=2000000) * (\x / 1000);
    }
}

\begin{tikzpicture}
\begin{axis}

%correct
\addplot[
    green,
    domain=50000:250000
] {correct(x)};
\addplot[
    green,
    domain=250001:500000
] {correct(x)};

%not correct
\addplot[
    red,
    domain=1000:200000
] {notCorrect(x)};
\addplot[
    red,
    domain=1000001:1500000
] {notCorrect(x)};

\end{axis}
\end{tikzpicture}
\end{document}

1 Answer 1

2

This is due to the "inaccuracy" of the math performed in TeX (itself). To circumvent this problem you could

  1. either use lualatex in combination with a compat level of 1.12 (or higher) or
  2. use gnuplot to calculate the values which are then just plotted by PGFPlots.

Please note that I reduced the absolute minimum to better show that both suggested solutions work as desired.

% used PGFPlots v1.14
    \RequirePackage{luatex85}
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
    \pgfplotsset{
        % use this `compat' level or higher in combination with lualatex
        % to get the desired result
        compat=1.12,
    }
\begin{document}
\tikzset{
    declare function={
        notCorrect(\x)= (\x<=1000000) * (0) +
            and(\x>1000000, \x<=2000000) * (\x / 1000);
    },
}
\begin{tikzpicture}
    \begin{axis}
        \addplot [
            red,ultra thick,
            domain=1000001:1500000,
        ] {notCorrect(x)};

        % use gnuplot to get the desired result
        % (remember to enable the "-shell-escape" feature)
        \addplot [
            green,dashed,ultra thick,
            domain=1000001:1500000,
            % I skipped the first part of the equation, because it is zero anyway
        ] gnuplot [id=notCorrect] {
            (x>1000000 && x<=2000000) * (x / 1000)
        };
    \end{axis}
\end{tikzpicture}
\end{document}

image showing the result of above code

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .