2

I want to draw a simple picture: lots of nodes and lines connecting them.

So I used foreach command to repeat -- (P\i) in \draw part.

\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\foreach[count=\i] \n in {1,3,2}{
    \node (P\i) at (\i,\n) {P\i};
%   \coordinate (P\i) at (\i,\n);
%   \node at (P\i) {P\i};
}
%\draw (P1) -- (P2) -- (P3);
\draw (P1) foreach \i in {2,3}{ -- (P\i)}; % <--- HERE!
\end{tikzpicture}
\end{document}

enter image description here

I expected it spells out (P1) -- (P2) -- (P3), but that's not. That command worked like

\draw (P1) -- (P2); \draw (P1) -- (P3);

I want to draw lines connecting P1, P2, P3, consecutively. If you change \node part to \coordinate command, it works well. It works like \draw (P1) -- (P2) -- (P3);.

\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\foreach[count=\i] \n in {1,3,2}{
%   \node (P\i) at (\i,\n) {P\i};
    \coordinate (P\i) at (\i,\n);
    \node at (P\i) {\i};
}
%\draw (P1) -- (P2) -- (P3);
\draw (P1) foreach \i in {2,3}{ -- (P\i)}; % <--- HERE!
\end{tikzpicture}
\end{document}

enter image description here

Why does not foreach work well for \node command?

3
  • It spells out: \draw (P1) -- (P2); \draw (P1) -- (P3); .
    – MS-SPO
    Commented Mar 24 at 13:55
  • @MS-SPO Could you change` \node` part to \coordinate (P\i) at (\I,\n);? Then, it spells out: \draw (P1) -- (P2) -- (P3);.
    – P.-S. Park
    Commented Mar 24 at 14:00
  • Try it, but I don’t think so. Coordinates are just nodes with zero dimensions, i.e. a point. If you don’t need to connect hundreds of nodes, it‘s easier and cleaner to just spell it out, like in your commented line. // Keep in mind, paths start with \ and end with ; So your 2nd loop just creates 2 pathes …
    – MS-SPO
    Commented Mar 24 at 14:07

1 Answer 1

3

It is possible to use the remember option of foreach

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach[count=\i] \n in {1,3,2}{
    \node (P\i) at (\i,\n) {\n};
}

\foreach [remember=\i as \lasti (initially 3)] \i in {1,2,3}{ \draw (P\i)--(P\lasti);};
\end{tikzpicture}
\end{document}

enter image description here

3
  • It's better for me to add some examples to the original question. Plz, read again.
    – P.-S. Park
    Commented Mar 25 at 1:37
  • Obviously this is a Tikz bug. You should report it here pgf/issues
    – AndréC
    Commented Mar 25 at 5:15
  • I see. I reported it. Thank you.
    – P.-S. Park
    Commented Mar 26 at 12:31

Not the answer you're looking for? Browse other questions tagged .