7

I have the following code:

\begin{tikzpicture}
    \begin{axis}    [
        axis lines = {center},
        width = {0.6\linewidth},
        ylabel = {$y$},
        xlabel = {$x$},
        ytick distance = {2},
        minor y tick num = {1}
        ]

    \addplot    [
                mark = none, domain= -3:4
                ]
                {abs(x)};
\end{axis}
\end{tikzpicture}

That produces the following image, notice close to x=0that there's a strange "break" on the function's plot. What could be the cause? How do I get rid of that?

Weird break next to x = 0

I noticed the problem also happens if I use a function with conditions say:

{x<0 ? -x+5 : x-2};

On the area near x=0 a weird break happens.

1 Answers1

16

Not strange, consider where the function value is calculated, by setting mark = x:

enter image description here

The default number of samples is 25, and 25 samples from -3 to 4 gives one sample at -0.0833 and the next at 0.20833. The asymmetry causes the problem you see.

If you set the number of samples and the domain such that you get a sample exactly at zero, you should be fine. With the domain -3:4, samples=8 or samples=15 for example will give you a sample at zero. Alternatively, for this specific case you can set samples at={-3,0,4}:

enter image description here

Complete code

\documentclass{article}

\usepackage{pgfplots} \begin{document}

\begin{tikzpicture} \begin{axis} [ axis lines = {center}, width = {0.6\linewidth}, ylabel = {$y$}, xlabel = {$x$}, ytick distance = {2}, minor y tick num = {1} ]

\addplot    [
            mark = none, samples at={-3,0,4}
            ]
            {abs(x)};

\end{axis} \end{tikzpicture}

\end{document}

Torbjørn T.
  • 206,688
  • My apologies for not accepting the answer earlier, I completely forgot. It's set now :) – Guilherme Vargas Aug 29 '16 at 17:55
  • There is also a big bug in pgfplots in the first picture. Please see: https://tex.stackexchange.com/questions/630075/severe-bug-in-pgfplots-in-certains-circonstances-on-y-axis-the-distance-from – quark67 Jan 13 '22 at 14:10