pgfplots 无法正确呈现图表 --- 出现奇怪的线条图案

pgfplots 无法正确呈现图表 --- 出现奇怪的线条图案

当我运行以下代码时

\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}

我得到了奇怪的输出:

在此处输入图片描述

我怎样才能使出现的奇怪线条图案变得平滑?

答案1

x=0因为除以 ,所以在 处有一个奇点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.001:20,
        y domain = 0:20 ]
        {cos(deg(y-x))/(x)};

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

在此处输入图片描述

当然,你也可以“治愈”该函数。输出几乎相同,但如果域扩展到负 ,这也有效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}

相关内容