Tikz foreach 效果不佳

Tikz foreach 效果不佳

我的目标是创建一个完整的二分图,并为顶点分配数字。我的想法是使用\foreach,它可以很好地创建顶点,但我无法添加数字。我应该尝试什么?

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{chains}



\begin{document}
\begin{tikzpicture}[thick,
  snode/.style={draw,fill=black,circle,scale=2},
  every node/.style={inner sep=1pt},
]



\begin{scope}[xshift=0cm,yshift=0cm,start chain=going right,node distance=7mm]
\foreach \i in {1,...,5}
  \node[snode,on chain] (g\i) {};
  \node [above=0.1cm of g\i] (y\i) {1}; %Missing \endcsname, Extra \endcsname
\end{scope}

\begin{scope}[xshift=0cm,yshift=-5cm,start chain=going right,node distance=7mm]
\foreach \i in {1,...,5}
  \node[snode,on chain] (h\i) {};
  \node [below = 0.1cm of h\i] (z\i) {2}; %problem with \endcsname
\end{scope}

\foreach \i in {1,...,5}
    \foreach \j in {1,...,5}
        \draw (g\i) -- (h\j);

\end{tikzpicture}
\end{document}

答案1

您可以添加一个label来代替第二个节点。

在此处输入图片描述

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{chains}



\begin{document}
\begin{tikzpicture}[thick,
  snode/.style={draw,fill=black,circle,scale=2},
  every node/.style={inner sep=1pt},
]



\begin{scope}[xshift=0cm,yshift=0cm,start chain=going right,node distance=7mm]
\foreach \i in {1,...,5}
  \node[snode,on chain,label=above:1] (g\i) {};
%  \node [above=0.1cm of g\i] (y\i) {1}; %Missing \endcsname, Extra \endcsname
\end{scope}

\begin{scope}[xshift=0cm,yshift=-5cm,start chain=going right,node distance=7mm]
\foreach \i in {1,...,5}
  \node[snode,on chain,label=below:2] (h\i) {};
%  \node [below = 0.1cm of h\i] (z\i) {2}; %problem with \endcsname
\end{scope}

\foreach \i in {1,...,5}
    \foreach \j in {1,...,5}
        \draw (g\i) -- (h\j);

\end{tikzpicture}
\end{document}

您可能对 TikZ 3 的绘图功能感兴趣。下面是一个简单的示例。但它不会重现代码的样式,只会重现结构。

在此处输入图片描述

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{graphdrawing,graphs}
\usegdlibrary{layered}
\begin{document}
\begin{tikzpicture}
\graph [layered layout,grow=down,sibling distance=2cm,layer distance=4cm]{
{a,b,c,d,e} --[complete bipartite] {f,g,h,i,j}
};
\end{tikzpicture}
\end{document}

相关内容