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}
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}
Why does not foreach work well for \node command?



\draw (P1) -- (P2); \draw (P1) -- (P3);. – MS-SPO Mar 24 '24 at 13:55\nodepart to\coordinate (P\i) at (\I,\n);? Then, it spells out:\draw (P1) -- (P2) -- (P3);. – P.-S. Park Mar 24 '24 at 14:00