点的分段函数

点的分段函数

如何按条件构造点以避免重复 \addplot

\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
    \begin{axis}
        \pgfplotsinvokeforeach{0.3,0.4,...,1} {
            \addplot coordinates { #1 < 1 ? (#1,#1) : (5,5)  }; % if \i < 1 then put (x,y) on axis,  else put (5,5) point on axis
        }
    \end{axis}
\end{tikzpicture}

\end{document}

答案1

您可以使用samples at

\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
    \begin{axis}
      \addplot[blue,mark=*,samples at={0.3,0.4,...,1}]  
      ({ifthenelse(x < 1,x,5)},{ifthenelse(x < 1,x,5)}); % if \i < 1 then put (x,y) on axis,  else put (5,5) point on axis
    \end{axis}
\end{tikzpicture}

\end{document}

在此处输入图片描述

可以让它更优雅一点declare function

\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}[declare function={f(\x)=ifthenelse(\x<1,\x,5);}]
    \begin{axis}
      \addplot[blue,mark=*,samples at={0.3,0.4,...,1}]  
      ({f(x)},{f(x)}); % if \i < 1 then put (x,y) on axis,  else put (5,5) point on axis
    \end{axis}
\end{tikzpicture}

\end{document}

或者,您可以构建一个列表并对其进行绘图。需要小心谨慎,因为当 pgf 使用 迭代列表时,它...会引入小错误,这就是条件读取\ifdim\i pt<0.98pt而不是 的原因\ifdim\i pt<1pt

\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}

\begin{tikzpicture}
    \begin{axis}
    \edef\mylst{}
    \pgfplotsforeachungrouped \i in {0.3,0.4,...,1}  {%
    \ifdim\i pt<0.98pt
     \edef\mylst{\mylst (\i,\i)}
    \else
     \edef\mylst{\mylst (5,5)}
    \fi
    }%
    \addplot coordinates {\mylst};
    \end{axis}
\end{tikzpicture}
\end{document}

相关内容