1. 程式人生 > 其它 >GraphViz 繪製圖形入門

GraphViz 繪製圖形入門

技術標籤:graphviz

DOT, GraphViz 簡介

  1. DOT 是一種文字圖形描述語言。DOT 語言檔案通常具有 .gv 或是 .dot 的副檔名。在編寫好 DOT 檔案之後,需要有專門的程式處理這些檔案並將其渲染成為圖片,dot 就是其中一款程式,它可以將 DOT 語言描述的圖形渲染成 GIF,PNG,SVG,PDF 等多種格式檔案。
  2. GraphViz 是一個開源軟體包,提供可以執行 DOT 檔案的 dot 程式。Graphviz 中包含了眾多的佈局器:
  • dot, 預設佈局方式,主要用於有向圖
  • neato, 基於 spring-model (又稱 force-based )演算法
  • twopi
    , 徑向佈局
  • circo, 圓環佈局
  • fdp, 用於無向圖

基本用法,以下語句繪製一個簡單的有向圖:

digraph G{
    a->b;
    b->d;
    c->d;
}

執行命令列 dot -Tsvg graphviz_example_1.dot -o graphviz_example_1.svg,上面的程式碼得到以下結果:

示例

  • 強調一條路徑
graph {
    rankdir=LR;
    a -- b -- d -- c -- f[color=red,penwidth=3.0];
    b -- c;
    d -- e;
    e -- f;
    a -- d;
}
  • 聚集子圖
digraph {
    subgraph cluster_0 {
        label="聚集子圖 1";
        a -> b;
        b -> c;
    }

    subgraph cluster_1 {
        label="聚集子圖 2";
        a -> f;
        f -> c;
    }
}

需要注意的是,子圖的名稱字首必須為 cluter 才可以顯示邊框及 label。

  • 自動機
digraph finite_state_machine {
	rankdir=LR;
	size="8,5"
	node [shape = doublecircle]; LR_0 LR_4;
	node [shape = circle];
	LR_0 -> LR_2 [ label = "SS(B)" ];
	LR_0 -> LR_1 [ label = "SS(S)" ];
	LR_2 -> LR_6 [ label = "SS(b)" ];
	LR_2 -> LR_5 [ label = "SS(a)" ];
	LR_2 -> LR_4 [ label = "S(A)" ];
	LR_5 -> LR_5 [ label = "S(a)" ];
	LR_6 -> LR_6 [ label = "S(b)" ];
	LR_6 -> LR_5 [ label = "S(a)" ];
}

DOT 語法

結點或者邊都可以通過語法 (node|edge) attr_list 指定屬性列表 attr_list,比如文字字型 family、大小、結點形狀、箭頭形狀、箭頭起始位置等等。關於屬性的選擇可以參考官方文件 https://www.graphviz.org/doc/info/attrs.html

digraph {
  Tinos [ fontname="Tinos" ];
  Handlee [ fontname="Handlee" ];
  "Sedgwick Ave" [ fontname="Sedgwick Ave" ];
  "*also Sedgwick*";
}

Graph 屬性

  • label="Simple_Graph" 為圖加 label
  • rankdir=LR 圖結構從左往右,預設 TB (top-bottom)
  • splines="line" 強制直邊,不要彎曲邊

Edge 屬性

  • graph 畫無向圖,diagraph 有向圖
  • 在邊上可以指定屬性,比如 hello -> world [ color="orange", penwidth=3.0 ]; 設定著色為橙色,penwidth 加粗邊

Others

  • 小技巧:有時候當結點及邊過多,結點的上下或者左右順序發生變化,我們可能新增隱形的邊來強制它們之間關係。比如 a->b [style=invisible, dir=none];

寫作主要參考