Tikz,graphdrawing:如何使用 \foreach 变量设置边缘节点标签?

Tikz,graphdrawing:如何使用 \foreach 变量设置边缘节点标签?

我想使用循环创建并标记边,\foreach以避免在创建大型图时必须写入每个节点/边。当我使用它创建节点时,它工作正常,但当我尝试使用变量标记边时,它停止工作。

我在这里给出了一个我想要绘制的示例,以及我尝试编写它的方式。我同时包括了使用引号符号和通常符号的尝试。当我将它们放在边缘标签应该在的位置node[]{}时,我收到未定义的控制序列错误。\x

我正在使用具有分层布局的图形绘制来绘制图形,我更喜欢一种可以继续使用它的解决方案,或者至少是一些等效的东西,以一种好的方式自动定位节点和边。

% !TeX program = lualatex

\documentclass{article} 
\usepackage{tikz}
\usetikzlibrary{graphs, graphdrawing, calc, quotes}
\usegdlibrary{layered}

\begin{document}

What I want in the end:

\begin{tikzpicture}[layered layout, nodes={circle,draw},level pre sep=1cm,every edge quotes/.style={auto,font=\footnotesize, draw=none, inner sep=0.1em},  horizontal=a to b ]


\node  (a) {a};
\node  (b) {b};

\foreach \x in {1,2,3} 
{ 
    \node (a\x) {$ a^\x $};

}

\draw (a) edge ["1" ,->] (a1); 
\draw (a1) edge [->] node[every edge quotes]{$a^1 $}  (b);
\draw (a) edge ["2" ,->] (a2);
\draw (a2) edge [->] node[every edge quotes]{$ a^2 $}  (b);
\draw (a) edge ["3" ,->] (a3);
\draw (a3) edge [->] node[every edge quotes]{$ a^3 $}  (b);

\end{tikzpicture}


How I tried to write it:

\begin{tikzpicture}[layered layout, nodes={circle,draw},level pre sep=1cm,every edge quotes/.style={auto,font=\footnotesize, draw=none, inner sep=0.1em},  horizontal=a to b ]


\node  (a) {a};
\node  (b) {b};

\foreach \x in {1,2,3} 
{ 
    \node (a\x) {$ a^\x $};
    \draw (a) edge ["\x" ,->] (a\x);
    \draw (a\x) edge [->] node[every edge quotes]{$ a^{\x} $}  (b);
}

\end{tikzpicture}
\end{document}

这是我运行上述代码时得到的结果。

答案1

欢迎来到不断膨胀的宇宙!这些都是膨胀问题。你可以用 pgfplots 来解决它们。

\documentclass{article} 
\usepackage{tikz}
\usetikzlibrary{graphs, graphdrawing, calc, quotes}
\usegdlibrary{layered}

\begin{document}

What I want in the end:

\begin{tikzpicture}[layered layout, nodes={circle,draw},level pre sep=1cm,every edge quotes/.style={auto,font=\footnotesize, draw=none, inner sep=0.1em},  horizontal=a to b ]


\node  (a) {a};
\node  (b) {b};

\foreach \x in {1,2,3} 
{ 
    \node (a\x) {$ a^\x $};

}

\draw (a) edge ["1" ,->] (a1); 
\draw (a1) edge [->] node[every edge quotes]{$a^1 $}  (b);
\draw (a) edge ["2" ,->] (a2);
\draw (a2) edge [->] node[every edge quotes]{$ a^2 $}  (b);
\draw (a) edge ["3" ,->] (a3);
\draw (a3) edge [->] node[every edge quotes]{$ a^3 $}  (b);

\end{tikzpicture}


How I tried to write it:

\begin{tikzpicture}[layered layout, nodes={circle,draw},level pre sep=1cm,every edge quotes/.style={auto,font=\footnotesize, draw=none, inner sep=0.1em},  horizontal=a to b ]


\node  (a) {a};
\node  (b) {b};

\foreach \X in {1,2,3} 
{ 
    \edef\temp{\noexpand\node (a\X) {$ a^\X $};}
    \temp
    \edef\temp{\noexpand\draw (a) edge ["\X" ,->] (a\X);}
    \temp
    \edef\temp{\noexpand\draw (a\X) 
    edge [->] node[every edge quotes]{$ a^{\X}  $}  (b);}
    \temp 
}

\end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容