Graphviz介绍

像写代码一样画图。

Graphviz是一个从dot语言生成图片的工具,下面是一个dot示例和它对应的图片:

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

相关链接:

Graphviz官网:https://graphviz.org/

dot语言官方文档:https://graphviz.org/doc/info/lang.html

dota语言维基百科:https://zh.wikipedia.org/wiki/DOT语言

测试工具:

在vscode上安装Graphviz (dot) language support for Visual Studio Code这个插件,创建dot文件,按Ctrl+Shift+P后输入Graphviz,选择Graphviz: Open Preview to the Side即可实时预览dot图片。

几个图形示例

示例来源:https://zh.wikipedia.org/wiki/DOT语言https://graphviztutorial.readthedocs.io/zh_CN/latest/index.html

无向图

graph {
    a -- b -- c;
    b -- d;
}

有向图

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

节点属性和边属性

digraph G {
    // label属性可以改变节点显示的名称
    a [label = "Foo"];
    // shape属性可以改变节点的形状
    b [shape = box];
    // color指定连接线的颜色
    a -> b -> c [color = blue];
    // style指定连接线的风格
    b -> d [style = dotted];
}

控制边的方向

digraph {
    a -> b [dir = both];
    b -> c [dir = none];
    c -> d [dir = back];
    d -> a [dir = forward];
}

控制边的起点位置和终点位置

digraph {
    // 统一将下面的节点设置成矩形
    node [shape = box];
    // n/e/s/w分别表示north, east, south, west, 可组合使用
    c1:n  -> d1    [label=n];
    c2:ne -> d2:ne [label=ne];
    c3:e  -> d3:ne [label=e];
    c4:se -> d4:n  [label=se];
    c5:s  -> d5:n  [label=s];
    c6:sw -> d6:n  [label=sw];
    c7:w  -> d7:nw [label=w];
    c8:nw -> d8:nw [label=nw];
}


Dot语法

整体语法如下:



1. 有向图用 digraph ,无向图用 graph ,有向图节点之间使用 -> 连接,无向图节点使用 -- 连接。

2. 支持注释,支持C风格的注释, /*...*/ 多行注释, // 单行注释,也可以用Shell风格的 # 开头的注释。

3. 语句结尾的分号可选。






















  • 无标签