我想请您帮助我解决\foreach
TikZ 包的以下应用。通过以下代码:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}\small
\foreach \x in {0,...,3}
\fill (\x,0) circle (2pt);
\foreach \x in {0,...,3}
\node[above=2pt] at (\x,0) {\x};
\foreach \x in {3.25,3.5,...,4.75}
\fill (\x,0) circle (0.5pt);
\foreach \x in {5,...,8}
\foreach \y in {1,...,4}
{
\fill (\x,0) circle (2pt);
\node[above=2pt] at (\x,0) {$n+\y$};
}
\foreach \x in {8.25,8.5,...,9.75}
\fill (\x,0) circle (0.5pt);
\end{tikzpicture}
\end{document}
我得到了下面的图片:
其中的参数\y
一个接一个地堆叠在一起。我的目标是n+1, ..., n+4
右侧点上方的标签。但我不知道如何告诉 TikZ 以这种方式使\y
参数依赖于\x
。我将不胜感激任何提示。
答案1
不需要嵌套循环,您只需使用一个简单的\foreach
选项count=
:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}\small
\foreach \x in {0,...,3}
\fill (\x,0) circle (2pt);
\foreach \x in {0,...,3}
\node[above=2pt] at (\x,0) {\x};
\foreach \x in {3.25,3.5,...,4.75}
\fill (\x,0) circle (0.5pt);
\foreach \x [count=\xi] in {5,...,8}
{
\fill (\x,0) circle (2pt);
\node[above=2pt] at (\x,0) {$n+\xi$};
}
\foreach \x in {8.25,8.5,...,9.75}
\fill (\x,0) circle (0.5pt);
\end{tikzpicture}
\end{document}
答案2
只是为了好玩,你可以foreach
按如下方式减少循环次数
% arara: pdflatex
% !arara: indent: {overwrite: yes}
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach \x [evaluate={\xi=int(\x-4);}] in {0,...,3,5,6,...,8}
{
\fill (\x,0) circle (2pt);
\ifnum\x<4
\node[above=2pt] at (\x,0) {\x};
\else
\node[above=2pt] at (\x,0) {$n+\xi$};
\fi
}
\foreach \x in {3.25,3.5,...,4.75,8.25,8.5,...,9.75}
\fill (\x,0) circle (0.5pt);
\end{tikzpicture}
\end{document}
这可能还可以进一步改进;
\begin{tikzpicture}
\foreach \x [evaluate={\xi=int(\x-4);}] in {0,...,3,5,6,...,8}
{
\node[fill,circle,inner sep=2pt,label={[above=2pt]90:{\ifnum\x<4\relax\x\else$n+\xi$\fi}}]
(n-\x) at (\x,0) {};
}
\draw[loosely dotted] (n-3) -- (n-5) (n-8) -- ++(2cm,0);
\end{tikzpicture}