This is my belated response to a self-identified dupe on TeX.SE.
Background
The list in a \foreach
loop is often long.
\foreach \pointA/\pointB in {{(1,0)}/{(2,2)},{(3,4)}/{(2,1)}} {
\draw \pointA -- \pointB;
}
Imagine having several other loop variables. The code inside the {…}
list
won’t be readable.
Problem
How can I make it looks smarter?
\foreach \pointA/\pointB in {
{(1,0)}/{(2,2)},{(3,4)}/{(2,1)}
} {
\draw \pointA -- \pointB;
}
doesn’t work.
Inspiration
Recently, I was asked the way to make two graphs to illustrate a complex function.
\begin{tikzpicture}
\pgfmathsetmacro\myLen{4};
\def\myshift#1{\raisebox{2ex}}
\begin{CJK}{UTF8}{bkai}
\foreach \x\hl\vl\gl\c [count=\xi] in {
0/x/y/{$z$-平面\\$z=x+iy$}/
{
(0.3*\myLen, 0.1*\myLen)
.. controls ++(165:-1) and ++(240: 1) .. ++(3, 2)
.. controls ++(240:-1) and ++(165:-1) .. ++(-1, 2)
.. controls ++(165: 1) and ++(175:-2) .. ++(-3, -2)
.. controls ++(175: 2) and ++(165: 1) .. cycle
},
{2*\myLen}/u/v/{$w$-平面\\$w=f(z)=u+iv$}/
{
(2.4*\myLen, 0.37*\myLen)
.. controls ++(200:-1) and ++(280: 1.65) .. ++(3, 2)
.. controls ++(280:-1.65) and ++(165:-1) .. ++(-1.5, -0.5)
.. controls ++(165: 1) and ++(175:-2) .. ++(-0.5, -1)
.. controls ++(175: 2) and ++(200: 1) .. cycle
}
} {
\draw[<->] (\x, \myLen) node[above] {$\vl$} -- ++(0,-\myLen) coordinate (O\xi) -- ++(\myLen,0) node[right] {$\hl$}
node[midway,anchor=north,below=.5cm,align=center,text width=4.5cm]{\gl};
\draw[yellow, thick] \c;
}
\draw[->,postaction={decorate,decoration={text along path,text align=center,text={|\itshape\myshift|f}}}]
($(O1) + (0.5*\myLen, 0.5*\myLen)$) to [bend left=25] ($(O2) + (0.5*\myLen, 0.5*\myLen)$);
\node[above, font=\huge] at (current bounding box.north) {\LaTeX{} 複函數圖像範例};
\end{CJK}
\end{tikzpicture}
Discussion
Thanks to the comments and ljguo’s answer, I know that PGFFor
parses \y in {{(0,0)}, {(1,3) }}
as
(0,0)
({}
taken away since)
and}
are consecutive characters.){(1,3) }
({}
preserved to keep the whitespace at the end.)
The EOL inside {}
is also parsed into whitespace by PGFFor.
Solution
Use %
to hide the EOL.
\foreach \pointA/\pointB in {
{(1,0)}/{(2,2)},{(3,4)}/{(2,1)}%
}{
\draw \pointA -- \pointB;
}