Tikz の foreach の使い方を練習した例。

参照:TikZ & PGF manual (version 3.0.1a)
https://ctan.org/pkg/pgf
83 Repeating Things: The Foreach Statement

foreach の繰り返し変数の使い方

\draw [help lines] (0,0) grid (4,3);

% foreach statement for nodes
\draw (0,0) node foreach \x in {0,1,2,3,4} at (\x, 0) {$x_\x$};


% 繰り返し回数 count 注意:1始まり
\foreach \x [count=\i] in {0, 1, ..., 4}
{
    \node(a\i) at (\x, 1) {$a_\i$};
}

% 0始まりでカウント
\foreach \x [count=\i from 0] in {0.0, 0.5, ..., 4.0}
{
    \node(b\i) at (\x, 2) {$b_\i$};
}

% 複数変数
\foreach \x / \y in {0/3, 1/2, 2/1, 3/0, 4/0}
{
    \draw [red] (\x,\y) circle (0.3);
}

% 演算結果 evaluate
\foreach \x [evaluate=\x as \y using 3-0.2*\x] in {0, 1, ..., 4}
{
    \fill [blue] (\x,\y) circle (0.1);
}

% 直前の値を記憶 remember
\node (P) at (0.5,0.5) {P};
\foreach \x / \y / \n [remember=\n as \npre (initially P)] in {2.5/0.5/Q, 2.5/1.5/R, 3.5/1.5/S}
{
    \node (\n) at (\x, \y) {\n}; 
    \draw (\npre) -- node[sloped,below,font=\tiny]{\npre\n} (\n);
}

結果

tikzforeach.png

Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account log in.