在 foreach 循环中绘制带有标记边的图形

在 foreach 循环中绘制带有标记边的图形

如何在图片示例中为每个边添加不同的标签。如何在 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}

输出

在此处输入图片描述

相关内容