为什么“\x-1”在节点名中不起作用?

为什么“\x-1”在节点名中不起作用?

如何修复使用引用节点时出现的错误\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-节点名称

我也尝试过

\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等等。因此,如果 TiZ 将节点名称解释为数字,否则就会变得模棱两可。

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}

在此处输入图片描述

相关内容