0

Here's a MWE to show what I mean:

\documentclass{minimal}
\usepackage{tikz}
\begin{document}
  \begin{tikzpicture}
    \foreach \x in {0, ..., 4}
    \node[circle,draw] (n\x) at ({2*\x}, 0) {\x};
    \foreach \x in {0, ..., 3} {
      \pgfmathsetmacro{\y}{\x+1}
      \draw[red] (n\x) to[bend left] (n\y);
      \draw[blue] (n\x) circle (.2);
      \draw[gray,fill] (n\y) circle (.05);
    }
  \end{tikzpicture}
\end{document}

I would expect this to create a few circular nodes, named n0 through n4, and connect subsequent pairs by lines going from edge to edge. However, while the (n\x) reference correctly refers to the node at \x, (n\y) in all instances somehow collapses to a single point, which is not even in the center:

Why does \y behave differently that \x?

I know how to make this work, for example using /pgf/foreach/remember, but I'm curious.

The Vee
  • 516

1 Answers1

1

When x = 0, \pgfmathsetmacro{\y}{\x+1} defines \y to 1.0. Then node n1.0 means a point at the boundary of node n1 and at angle 0.

To get \y defined to 1, here you can use one of the following (the last two are both suggested by @Alenanno from this comment),

  • pgfmath function int: \pgfmathsetmacro{\y}{int(\x+1)},
  • pgfmath macro \pgfmathtruncatemacro: \pgfmathtruncatemacro{\y}{\x+1}, and
  • pgffor option evaluate accompanied by int function: \foreach \x [evaluate=\x as \y using int(\x+1)] in {0, ..., 3} {...}.
\documentclass{minimal}
\usepackage{tikz}
\begin{document}
  \begin{tikzpicture}
    \foreach \x in {0, ..., 4}
      \node[circle,draw] (n\x) at ({2*\x}, 0) {\x};
    \foreach \x in {0, ..., 3} {
      \pgfmathsetmacro{\y}{int(\x+1)}
      \draw[red] (n\x) to[bend left] (n\y);
      \draw[blue] (n\x) circle (.2);
      \draw[gray,fill] (n\y) circle (.05);
    }
  \end{tikzpicture}
\end{document}

enter image description here

muzimuzhi Z
  • 26,474