![在 foreach 循环中绘制带有标记边的图形](https://linux22.com/image/317517/%E5%9C%A8%20foreach%20%E5%BE%AA%E7%8E%AF%E4%B8%AD%E7%BB%98%E5%88%B6%E5%B8%A6%E6%9C%89%E6%A0%87%E8%AE%B0%E8%BE%B9%E7%9A%84%E5%9B%BE%E5%BD%A2.png)
如何在图片示例中为每个边添加不同的标签。如何在 foreach 循环中执行此操作?
\begin{tikzpicture}
[scale=.8,auto=left,every node/.style={circle,fill=blue!20}]
\node (n6) at (1,10) {6};
\node (n4) at (4,8) {4};
\node (n5) at (8,9) {5};
\node (n1) at (11,8) {1};
\node (n2) at (9,6) {2};
\node (n3) at (5,5) {3};
\foreach \from/\to in {n6/n4,n4/n5,n5/n1,n1/n2,n2/n5,n2/n3,n3/n4}
\draw (\from) -- (\to);
\end{tikzpicture}
答案1
要么使用第三个变量,西格尔建议,或者使用以下ifcase
结构:
代码
\documentclass[tikz,border=2mm]{standalone}
\begin{document}
\begin{tikzpicture}
[ scale=0.8, auto=left,
every node/.style={circle,fill=blue!20},
lnode/.style={rectangle,fill=none},
]
\node (n6) at (1,10) {6};
\node (n4) at (4,8) {4};
\node (n5) at (8,9) {5};
\node (n1) at (11,8) {1};
\node (n2) at (9,6) {2};
\node (n3) at (5,5) {3};
\foreach \from/\to/\lbl in {n6/n4/24,n4/n5/20,n5/n1/5,n1/n2/2,n2/n5/10,n2/n3/6,n3/n4/12}
\draw (\from) -- node[above,sloped,lnode] {\lbl} (\to);
\end{tikzpicture}
\newcommand{\labeltext}[1]
{ \ifcase#1
\or 24
\or 20
\or 5
\or 2
\or 10
\or 6
\or 12
\fi
}
\begin{tikzpicture}
[ scale=0.8, auto=left,
every node/.style={circle,fill=blue!20},
lnode/.style={rectangle,fill=none},
]
\node (n6) at (1,10) {6};
\node (n4) at (4,8) {4};
\node (n5) at (8,9) {5};
\node (n1) at (11,8) {1};
\node (n2) at (9,6) {2};
\node (n3) at (5,5) {3};
\foreach \from/\to [count=\c] in {n6/n4,n4/n5,n5/n1,n1/n2,n2/n5,n2/n3,n3/n4}
{
\draw (\from) -- node[above,sloped,lnode] {\labeltext{\c}} (\to);
}
\end{tikzpicture}
\end{document}