我正在尝试绘制一个上下移动的函数,这是我所拥有的,也许它更清楚地说明了我想要什么:
\documentclass{minimal}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw (0,5) -- (0,0) -- (10,0);
\foreach \n in {1,...,20}
{
\node (a\n) at ({10-(10/\n)},0) {};
\node (b\n) at ({10-((10*\n + 5)/(\n*\n + \n))},5) {};
\draw (a\n) -- (b\n);
}
\end{tikzpicture}
\end{document}
但是在连接顶点和底点时遇到了问题,在代码中我想要一条从 b\n 到 a\n+1 的线。我尝试使用evaluate
如下方法:
\begin{tikzpicture}
\draw (0,5) -- (0,0) -- (10,0);
\foreach \n [evaluate=\n as \m using {int(\n+1)}] in {1,...,20}
{
\node (a\n) at ({10-(10/\n)},0) {};
\node (b\n) at ({10-((10*\n + 5)/(\n*\n + \n))},5) {};
\draw (a\n) -- (b\n);
\draw (b\n) -- (a\m); %this is not working
}
\end{tikzpicture}
并\pgfmathtruncatemacro
添加一些我认为可以停止尝试从 b20 到 a21(不存在的节点)画一条线:
\begin{tikzpicture}
\draw (0,5) -- (0,0) -- (10,0);
\foreach \n in {1,...,20}
{
\pgfmathtruncatemacro{\m}{\n + 1};
\node (a\n) at ({10-(10/\n)},0) {};
\node (b\n) at ({10-((10*\n + 5)/(\n*\n + \n))},5) {};
\draw (a\n) -- (b\n);
\draw (b\n) -- (a\m); %this is not working
\ifnum \m<20
\breakforeach
\fi
}
\end{tikzpicture}
但无论如何,编译器都会说:! Package pgf Error: No shape named a2 is known
。因此,任何能帮助解决我的问题的帮助都将不胜感激。
答案1
像这样吗?(请注意,我用minimal
standalone 和node
by替换coordinate
以避免出现间隙。)
\documentclass[tikz,border=3mm]{standalone}
\begin{document}
\begin{tikzpicture}
\draw (0,5) -- (0,0) -- (10,0);
\foreach \n in {1,...,20}
{
\coordinate (a\n) at ({10-(10/\n)},0) {};
\coordinate (b\n) at ({10-((10*\n + 5)/(\n*\n + \n))},5) {};
\draw \ifnum\n>1 (b\the\numexpr\n-1) -- \fi (a\n) -- (b\n);
}
\end{tikzpicture}
\end{document}