4

Consider the (currently incorrect) MWE:

\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{shapes,arrows,calc}

\begin{document}
\begin{tikzpicture}[node distance=2cm, auto]

\def\mypoints{(1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (5, 1), (4, 1), (3, 1), (2, 1), (1, 1)};
\def\lastnode{(1,0)};
\foreach \x in \mypoints { 
    \draw[fill] \x circle (0.05);   
    \path[draw, -latex', black!50!white] \x -| \lastnode;
    \let\lastnode=\x;
};

\end{tikzpicture}
\end{document}

My goal is to iterate through a list of points, either defined as such or generated through a \foreach range, and draw a circle/node/rectangle/etc at each point and then draw an arrow or other line to that point from the previous iteration.

What I thought would work is to create a trailer variable that maintains the state of the most recently drawn node, then use that information to draw the connecting lines easily. Currently the \lastnode variable is not updating, most likely because I am using the wrong macro for the job...

Is it possible to use the above outlined method to draw and connect nodes/points/... iteratively, or is another approach more appropriate? Ideally, the solution would work with both points (x, y) and named nodes (nodenumber1).

  • Thanks @TorbjørnT. I have located it in the manual, the remember option works like a charm. – pateryan Aug 10 '17 at 21:23
6

The following example defines nodes node1, node2, ... and draw edges between them. The option remember for \foreach allows to save some values from the previous loop pass.

\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{shapes,arrows,calc}

\begin{document}
\begin{tikzpicture}[node distance=2cm, auto]

\def\mypoints{%
  (1, 0), (2, 0), (3, 0), (4, 0), (5, 0),
  (5, 1), (4, 1), (3, 1), (2, 1), (1, 1)%
};
\path
  \foreach \x [count=\xi] in \mypoints {
    \x node[circle, fill, inner sep=sqrt(2)*0.025cm] (node\xi) {}
  }
  \foreach \x [count=\xi, remember=\xi-1 as \xiprev] in \mypoints {
    \ifnum\xi>1 %
      (node\xiprev) edge[-latex', black!50!white] (node\xi)
    \fi
  }
;
\end{tikzpicture}
\end{document}

Result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.