TikZ-pgf 並透過引用現有節點使用圖形繪製演算法

TikZ-pgf 並透過引用現有節點使用圖形繪製演算法

我想使用graphsTikZ 中的函式庫和graphdrawing演算法來建立一個包含許多節點的圖,以及稍後我將建立和標記的連線。

我有一個更複雜的版本:

\tikz [nodes={fill=white, font=\footnotesize},
>={Stealth[round,sep]}]
\graph[layered layout, branch down sep, nodes=draw, edges=rounded corners]
{
"cat" -- "dog" -- {"cow", "goat", "sheep"};
"cow" -- "bull";
"dog" -- "rooster" -- "duck";
};

我想做的是列出節點預先,並將它們標記為例如 a、b、c。然後我想在創建鏈時使用參考標籤。

我想這樣做的原因是因為每個節點的實際文字比“cat”長很多,我想避免每次想要建立新連線時輸入“supercalifragalistic”的混亂。

理想情況下我會有這樣的東西:

\begin{tikzpicture}
\tikz [nodes={fill=white, font=\footnotesize},
>={Stealth[round,sep]}]
\node (a) {cat}; 
\node (b) {dog};
\node (c) {cow};
\node (d) {goat};
\node (e) {sheep};
\node (f) {bull};
\node (g) {rooster};
\node (i) {duck};
\graph[use existing nodes = true, layered layout, branch down sep, nodes=draw, edges=rounded corners]
{
"cat" -- "dog" -- {"cow", "goat", "sheep"};
"cow" -- "bull";
"dog" -- "rooster" -- "duck";
(a) -- (b) -- { (c), (d), (e)};
(c) -- (f);
(b) -- (g) -- (i);
};
\end{tikzpicture}

但我用這種方法遇到了錯誤,包括attempting to create edge between nodes that are not in the graph.

這可能嗎?我看到了一種稍微不同的方法,但確實有效,如下所示:

\begin{tikzpicture}[new set=import nodes]
\begin{scope}[nodes={set=import nodes}] % make all nodes part of this set
\node [red] (a) at (0,1) {$a$};
\node [red] (b) at (1,1) {$b$};
\node [red] (d) at (2,1) {$d$};
\end{scope}
\graph{
(import nodes);
% "import" the nodes
a -> b -> c -> d -> e;
};
\end{tikzpicture}

但這裡沒有圖形繪製演算法(layered layout),並且您必須指定節點的位置,這是我想避免的。

答案1

您可以只聲明它們而不使用連接它們

<node name>/<node text>

句法。

然後<node name>在實際連接節點時透過引用它們。

程式碼

\documentclass[tikz,convert]{standalone}
\usetikzlibrary{arrows.meta,graphs,graphdrawing}
\usegdlibrary{layered}
\begin{document}
\tikz[
  nodes={fill=white, font=\footnotesize},
  >={Stealth[round,sep]}
]
\graph[
  layered layout,
  branch down sep,
  nodes={draw, text height=height("a"), text depth=+0pt},
  edges=rounded corners
] {
  a/cat, b/dog, c/cow, d/goat, e/sheep, f/bull, g/rooster, i/duck,
  a -- b -- {c, d, e},
  c -- f,
  b -- g -- i,
};
\end{document}

輸出

在此輸入影像描述

相關內容