TransWikia.com

pgfplots does not render the plot properly --- strange line pattern appearing

TeX - LaTeX Asked on March 25, 2021

When I run the following code

documentclass{article}
usepackage{pgfplots}
pgfplotsset{compat=1.8}

begin{document}
begin{tikzpicture}
begin{axis}[colorbar,
    colorbar style={
        ytick={-1,0,1},
        yticklabels={$-1$, $0$, $1$},},
    ylabel = $y$,
    xlabel = $x$,
    domain = 0:20,
    y domain = 0:20,
    view = {0}{90},
    point meta min=-1,
    point meta max=1,
    ymax=20,
    ]

    addplot3[
        surf,shader=interp,
        samples=50,
        domain = 0:20,
        y domain = 0:20 ]
        {cos(deg(y-x))/(x)};

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

I get the strange output:

enter image description here

How do I smooth out the strange pattern of lines that’s appearing?

One Answer

There is a singularity at x=0 because you divide by x. One way to avoid the problem is to adjust the domain to avoid the problematic points.

documentclass{article}
usepackage{pgfplots}
pgfplotsset{compat=1.17}

begin{document}
begin{tikzpicture}
begin{axis}[colorbar,
    colorbar style={
        ytick={-1,0,1},
        yticklabels={$-1$, $0$, $1$},},
    ylabel = $y$,
    xlabel = $x$,
    domain = 0:20,
    y domain = 0:20,
    view = {0}{90},
    point meta min=-1,
    point meta max=1,
    ymax=20,
    ]

    addplot3[surf,shader=interp,
        samples=50,
        domain = 0.001:20,
        y domain = 0:20 ]
        {cos(deg(y-x))/(x)};

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

enter image description here

Of course, you can also "cure" the function. The output is virtually the same, but this also works if the domain extends to negative x.

documentclass{article}
usepackage{pgfplots}
pgfplotsset{compat=1.17}

begin{document}
begin{tikzpicture}
begin{axis}[colorbar,
    colorbar style={
        ytick={-1,0,1},
        yticklabels={$-1$, $0$, $1$},},
    ylabel = $y$,
    xlabel = $x$,
    domain = 0:20,
    y domain = 0:20,
    view = {0}{90},
    point meta min=-1,
    point meta max=1,
    ymax=20,
    ]

    addplot3[surf,shader=interp,
        samples=50,
        domain = 0:20,
        y domain = 0:20 ]
        {x==0?sign(cos(deg(y))):cos(deg(y-x))/(x)};

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

Correct answer by user237299 on March 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP