前言
之前我的博客介绍了Graphviz 画图教程,虽然dot语法类似C语言容易编写和理解,但是这仅限于小图,当你想要画一个大图的时候,每一个结点都得一个个去定义名字、属性、连接线,这无疑是十分麻烦的,这种时候就想到了Python,能否利用Python语言编写一个画图脚本呢?
Graphviz库
幸运的是,Python正好有一个Graphviz库,Github地址
安装也是十分简单,只需要一行代码:
pip install graphviz
开始
Digraph(一)
本次博客的代码直接在Jupyter上运行,方便显示结果
from graphviz import Digraph
dot = Digraph(comment='The Round Table')
dot.node('A', 'King Arthur')
dot.node('B', 'Sir Bedevere the Wise')
dot.node('L', 'Sir Lancelot the Brave')
dot.edges(['AB', 'AL'])
dot.edge('B', 'L', constraint='false')
dot
Dot代码
// The Round Table
digraph {
A [label="King Arthur"]
B [label="Sir Bedevere the Wise"]
L [label="Sir Lancelot the Brave"]
A -> B
A -> L
B -> L [constraint=false]
}
Digraph(二)
from graphviz import Digraph
f = Digraph('finite_state_machine', filename='fsm.gv')
f.attr(rankdir='LR', size='8,5')
f