如何修复使用引用节点时出现的错误\x-1
?
它在 中可以工作[below left = \x-1]
,但在 中不工作\draw[->] (\x-1) to (\x)
。
\documentclass[tikz]{standalone}
\usepackage{pgffor,pgfmath}
\usetikzlibrary{positioning, arrows.meta}
\begin{document}
\begin{tikzpicture}[node distance = 1.00cm and 0.10cm,
every node/.style = {draw, circle, fill = blue!20}]
\node (1) {$1$};
\foreach \x in {2, ..., 7} {
\node (\x) [below left = \x-1] {$\x$};
\draw[->] (\x-1) to (\x); % not work: no shape named 2-1
}
\end{tikzpicture}
\end{document}
我也尝试过
\foreach \x [remember = \x as \lastx] in {2, ..., 7} {
\node (\x) [below left = \x-1] {$\x$};
\draw[->] (\lastx) to (\x); % not work: undefined control sequence. \lastx }
}
答案1
\x-1
被评估为2-1
等 Ti钾出于充分的理由,Z 并不(必然)期望此位置有一个数字。1.north
您也可以写1.90
,例如1.east
1.0
等等。因此,如果 Ti钾Z 将节点名称解释为数字,否则就会变得模棱两可。
remember
但是,如果我添加适当的初始值(对于第一步),我不会遇到任何问题。
\documentclass[tikz]{standalone}
\usepackage{pgffor,pgfmath}
\usetikzlibrary{positioning, arrows.meta}
\begin{document}
\begin{tikzpicture}[node distance = 1.00cm and 0.10cm,
every node/.style = {draw, circle, fill = blue!20}]
\node (1) {$1$};
\foreach \x [remember=\x as \lastx (initially 1)] in {2, ..., 7} {
\node (\x) [below left = \x-1] {$\x$};
\draw[->] (\lastx) to (\x); % not work: no shape named 2-1
}
\end{tikzpicture}
\end{document}
答案2
\x-1
不在节点名称位置内进行评估,但您可以在构造的可选参数内强制进行一些评估\foreach
。
\documentclass[tikz]{standalone}
\usepackage{pgffor,pgfmath}
\usetikzlibrary{positioning, arrows.meta}
\begin{document}
\begin{tikzpicture}[node distance = 1.00cm and 0.10cm,
every node/.style = {draw, circle, fill = blue!20}]
\node (1) {$1$};
\foreach \x [evaluate=\x as \nx using {int(\x-1)}] in {2, ..., 7} {
\node (\x) [below left = of \nx] {$\x$};
\draw[->] (\nx) to (\x); % not work: no shape named 2-1
}
\end{tikzpicture}
\end{document}
注意:我还添加了of
定位构造(您正在加载positioning
库),结果有点不同。
答案3
您可以使用 强制完成整数求值\numexpr
。
\documentclass[tikz]{standalone}
\usepackage{pgffor,pgfmath}
\usetikzlibrary{positioning, arrows.meta}
\begin{document}
\begin{tikzpicture}[node distance = 1.00cm and 0.10cm,
every node/.style = {draw, circle, fill = blue!20}]
\node (1) {$1$};
\foreach \x in {2, ..., 7} {
\node (\x) [below left = \x-1] {$\x$};
\draw[->] (\the\numexpr\x-1\relax) to (\x);
}
\end{tikzpicture}
\end{document}