Graphviz
官网下载好对应系统的版本并安装 ,在terminal中输入
dot -version
可以检查安装是否成功。若未出现相应的版本信息,可以考虑配置环境变量或者重新安装。
1. 基本语法
和C语言一样,Graphviz也有一些关键字,不能作为自定义变量,以下是几个基本的关键字:
graph:定义无向图,描述为a--b
digraph:定义有向图,描述为a->b
subgraph:定义子图,子图可以单独用框框出
strict :禁止了多条线的创建,有向图中,从一个节点指向另一个节点的线只能由一条;无向图中,两个节点中只能有一条线连接。例如:有向图带有strict和不带strict的区别:
[strict]digraph {
a -> b
a -> b
b -> a [color=red]
b -> a [color=red]
}
一个整体的代码结构,下面只列举一些常用的属性,需要使用更多属性可以查看官网相关文档:
[strict](graph | digraph)[ID]
{
/* 声明一些图的属性 [Attributes] 每条语句结尾可以用;相隔,也可省略不写*/
layout=neato # 定义作图的引擎,可以改变node的组合形式,可选:dot、neato、 fdp、 patchwork
rankdir= "RL" # 定义箭头的指向,可选"LR" 、“BT”(Botton->top)、"TB"
labeljust=l #调整label位置,左(l) 中(c) 右(r)
graph [class="ClassA"] # 定义分类
bgcolor=lightgray # 图背景颜色
color="yellow" # 框颜色
node [shape=record,color = red,fillcolor=yellow, style="rounded,filled"] #定义node的全局属性
# shape定义node形状;style定义node的属性:filled(填充)、rounded(圆角)
edge [style = dotted,weight=8,color=red] # 定义edge的全局属性
# style定义线的类型,可选:dotted(虚线),bold(加粗),invis(隐藏)
# weight定义线宽;color定义线的颜色
subgraph cluster # 定义子图
{
/*[Attributes], 子图的属性可以参考以上关于图的属性*/
# 除了node和edge定义的全局属性,还可以在语句后加[]特化某个node或者edge
NodeA [label="{ a | b | c }"] # 多个label可以用 | 分隔
NodeB [label="<f0> one|<f1> two"] # f0 f2 f3...分别表示了一个node中的不同位置。
# 一个节点也可以指向多个节点:
A -- {B;C} # 等价于 A -- B A -- C
# 无向图
# NodeA -- NodeB [style = dotted,label="It is an edge"]
#有向图
# NodeA -> NodeB [dir=forward] # 可选back、both、none定义箭头的指向。
# NodeA -> NodeB [arrowhead = diamond] # 定义箭头的样式。
15:f0:n->7:f1:se; # 选项: [(n | ne | e | se | s | sw | w | nw | c | _)]
}
}
以下属性可以作用于graph、subgraph、edge、node:
label="It is a graph" # 自定义标签
fontname="Comic Sans MS" # 设置字体,默认为"Times-Roman"
fontsize="40" # 设置字体大小
fontcolor = red # 设置字体颜色
补充
2. 编译运行
一个在线查看结果的网址
- (不推荐)可以直接在命令行中输入代码,软件会在当前文件夹下生成图片。基本思路就是利用管道编译并将结果重定向或者输出。缺点就是如果做复杂的图,要输入的命令很长,也不容易debug。
echo 'graph { a -- b }' | dot -Tpng -o out.png
- 可以在当前文件夹下新建
.dot
结尾的文本文件test.dot
,然后在文件中编辑
graph { a -- b }
然后在命令行输入:
dot -Tpng test.dot -o test.png #小写o
dot -Tpng test.dot > test.png #重定向形式
dot -Tpng -O test.dot #若不指定生成的文件,可使用大写O,会根据-T自动生成相应后缀文件
# 其他:
dot -? #查看其他选项
Graphviz可以生成多种文件格式,具体可以查看文档。
- 若觉得在命令行输入命令太麻烦,可以编写
makefile
。例如:
test.png:test.dot
dot -Tpng -O $^
.PHONY:clean
clean:
rm -f *.png
当然在Windows中可以使用一些IDE,vscode或者Sublime;以Subline为例,简单配置一下,按键Ctrl + B
就可以方便输出了。
3. 一些例子
3.1 一个简单的二叉树
digraph BinaryTree {
a -> b
a -> c
b -> d
d [label="null"];
node1[shape=point, style=invis]
b -> node1[weight=10, style=invis]
b -> e
c -> f
node2[shape=point, style=invis]
c -> node2[weight=10, style=invis]
c -> g
g [label="null"];
e -> h
h [label="null"];
node3[shape=point, style=invis]
e -> node3[weight=10, style=invis]
e -> i
i [label="null"];
f -> k
k [label="null"];
node4[shape=point, style=invis]
f -> node4[weight=10, style=invis]
f -> j
j [label="null"];
}