
如何透過條件構造點避免重複 \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}