给定加权有向图的邻接矩阵,如何在没有权重的情况下在 Tikz 中绘制这样的图?

给定加权有向图的邻接矩阵,如何在没有权重的情况下在 Tikz 中绘制这样的图?

我有一个有向加权图的邻接矩阵。我想用 tikz 绘制这个图。我的邻接矩阵大小为 50 x 50,并且是 txt 格式。显然,最好有使用 txt 文件的代码,并且自动定位节点,因为我没有位置。谢谢您的帮助!

答案1

五十个节点将会很混乱,但这里只有九个节点。

对于实际使用,请删除注释的行fake并取消注释,real该行实际上设置了权重/矩阵给出的权重,例如

weights/matrix={{1,2,3},{4,5,6},{7,8,9}}

对于 3×3 矩阵

1 2 3
4 5 6
7 8 9


这显然难以辨认,但我愿意听取建议。
不旋转?白色背景?线宽?虚线图案?颜色?

利用该graphdrawing库,也许可以实现更好的布局,特别是当许多边的权重为零时。

代码

\documentclass[tikz]{standalone}
\usepackage{amsmath}% for \overset
\usetikzlibrary{
  graphs.standard, % for \graph and subgraph I_n
  quotes,          % "nodes" on edges
  ext.misc}        % for /utils/TeX/ifnum
\tikzset{
  weights/matrix/.style={
    /utils/exec=\def\listrow{0},
    /utils/rows/.style={
      /utils/exec=\def\listcol{0}\edef\listrow{\the\numexpr\listrow+1\relax},
      /utils/cols/.estyle={/utils/exec=\edef\noexpand\listcol{\noexpand\the\numexpr\noexpand\listcol+1\relax},
        /tikz/weights/weight \listrow-\noexpand\listcol/.initial/.evaluated={random(0,9)}% fake
%        /tikz/weights/weight \listrow-\noexpand\listcol/.initial={####1}% real
      }, /utils/cols/.list={##1},
    }, /utils/rows/.list={#1}}}
\begin{document}
\begin{tikzpicture}[
  weights/matrix={% include actual weights here
    {,,,,,,,,},
    {,,,,,,,,},
    {,,,,,,,,},
    {,,,,,,,,},
    {,,,,,,,,},
    {,,,,,,,,},
    {,,,,,,,,},
    {,,,,,,,,},
    {,,,,,,,,}},
]
\graph [
  clockwise, % place nodes in a circle
  radius=5cm,% of this radius
  nodes={circle, draw},
  do edge/.style 2 args={
    % if the weight is 0 → ignore edge
    /utils/TeX/ifnum={\pgfkeysvalueof{/tikz/weights/weight #1-#2}=0}{}{
      /utils/TeX/ifnum={#1=#2}{
        % if row = col → just add label
        parse={#1[label={[anchor=west]west:%
          \pgfkeysvalueof{/tikz/weights/weight #1-#2}}]}
      }{% otherwise draw edge and add weight as a label
        parse={#1 --[
          "$#1\overset{\pgfkeysvalueof{/tikz/weights/weight #1-#2}}{\to}#2$"{
            sloped, allow upside down}] #2}}}}
]{
  subgraph I_n[n=9];
  {[
    /tikz/every node/.append style={font=\scriptsize, inner ysep=+.4ex},
    /tikz/every label/.append style={inner sep=+.1em},
  ] \foreach \row in {1,...,9} {
      \foreach \col in {1,...,9} {
        [do edge=\row\col]}}}};
\end{tikzpicture}
\end{document}

输出

在此处输入图片描述

相关内容