在使用pprof
分析go
的項目時,經常會查看各項指標的有向圖
原理是使用Graphviz
(Graph Visualization Software)解析生成的dot
腳本得到最終展示給我們的圖信息。
dot
是Graphviz
用於畫有向圖和無向圖語言,語法簡單。
dot
的抽象語法
[ strict ] (graph | digraph) [ ID ] '{' stmt_list '}'
dot
支持無向圖graph
和有向圖digraph
的繪制,無向圖可以理解為沒有箭頭的有向圖,我們直接可以在有向圖的edge
上使用屬性dir=none
下面的無象圖graph
和有向圖digraph
結果是一樣的
graph G1 {
a -- b;
a -- d;
b -- c;
d -- c;
}
digraph G1 {
edge [dir=none];
a -> b;
a -> d;
b -> c;
d -> c;
}
注意無向圖(graph)的邊用的是--
而有向圖(digraph)用的是->
,除了這點,其他的屬性基本都是通用的。
關鍵字
- node:節點屬性
- edge:連線屬性
- graph:圖屬性,或聲明一個無向圖時使用
- digraph:有向圖
- subgraph:聲明子視圖,名字要以
cluster
開頭。 - strict:嚴格模式,用於防止相同的兩個節點間使用重復的連線。
節點和屬性
聲明一個節點直接輸入節點的名字就可以,如果有多個節點在同一行可以使用空格或者;
進行分隔。
digraph G1 {
a;
b; c;
"x.y";
}
如果節點的名字有特殊比如.
可以用雙引號把字符串包起來
邊
兩個節點直連,可以直接用->
相連可以,如果一個節點連接多個其他的節點我們可以用{}
把節點包起來如下面的a -> {d; "x.y"};
digraph G1 {
a -> b;
a -> c [dir=back];
a -> {d; "x.y"};
}
如果想要控制邊的方向可以使用dir
屬性,比如 a -> c [dir=back];
label
dot
可以為所有的元素添(graph
, node
, edge
)加label
,比如我們的node
默認情況下顯示的就是他的名字。如果我們想換一個名字可以使用label
來進行修改,label
不僅支付字符串,而且支持html
,html
內容要放在要用<>
。
如果 shape= record
label
還可以創建分組
digraph G {
label = "https://github.com/lpxxn"
n1 [label="hello world"];
a -> b[label=abc];
c [label=<Test<BR /><FONT POINT-SIZE="10">Group: g2</FONT>>; color=orange];
d [shape = record, label="{x|y|z}"]
}
屬性
節點和邊只是最基本的需求,我們想要圖、節點和邊的顏色都不相同
digraph G1 {
graph[bgcolor=lightblue];
a [color=blue; style=filled; fontcolor=green];
a -> b [color=red; label=A];
edge [color=green]
a -> {c; "x.y"};
}
graph
全局圖屬性,比如我們把背景顏色變也了淡藍色,圖屬性是全局的,除了在graph[]
里使用,我們也可以在graph[]
外使用,比如控制圖的方向rankdir=LR
node
全局節點屬性,我們可以控制全局的節點屬性比如我們可以控制所有節點的形狀
edge
全局的邊屬性
下面就是把圖,節點和邊的屬性進行了簡單設置
digraph G1 {
graph[bgcolor=lightblue];
rankdir=LR
node[shape=box];
a [color=blue; style=filled; fontcolor=green];
a -> b [color=red; label=A; dir=back];
edge [color=green]
a -> {c; "x.y"};
"x.y" -> "x.y";
}
子視圖
一個視圖可以包含多個子視圖,子視圖的名字必須要以cluster
開頭。
子視圖內的節點相連接,如果不想尾部在子視圖內,要使用compound=true
屬性,連線要加上ltail=cluster_2
告訴引擎尾部在哪里。
digraph G1 {
rankdir=RL;
graph [compound=true];
subgraph cluster_1 {
label = "https://github.com/lpxxn";
edge [dir=none, color=green];
A; B; C;
};
N1 [shape=diamond label=<hello<BR /><FONT POINT-SIZE="10">world</FONT>> color=orange];
subgraph cluster_2 {
label = "https://github.com/lpxxn";
edge [color=red];
D; E;
};
D -> N1 [ltail=cluster_2];
N1 -> B;
E -> C;
}
總結
除了上面提到的一些屬性還有很多其他的功能,比如箭頭的樣式等等。可以參考文檔
圖 : https://graphviz.org/doc/info/attrs.html
形狀: https://graphviz.org/doc/info/shapes.html
箭頭: https://graphviz.org/doc/info/arrows.html