簡介
自己在繪制流程圖的時(shí)候一般用到的是Visio混卵,但是感覺連線以及框圖位置調(diào)整起來很煩…經(jīng)過一番了解之后發(fā)現(xiàn)了Graphviz可以使用Python代碼來繪制流程圖的軟件,使用這個(gè)工具我們可以更專注于關(guān)系之間的表示而不是繪制的方法窖张。先來看看一個(gè)神經(jīng)網(wǎng)絡(luò)的效果圖吧:(Ref:https://blog.csdn.net/ztguang/article/details/77451803):
下載安裝
對(duì)于Python包來說直接一句pip install graphviz
即可幕随,參考
Graphviz Docs
來試一下:
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.view()
報(bào)錯(cuò)了?
ExecutableNotFound: failed to execute ['dot', '-Tpdf', '-O', 'Digraph.gv'], make sure the Graphviz executables are on your systems' PATH
意思就是沒有加入系統(tǒng)路徑宿接,所以再從官網(wǎng)上下載dot
這些命令的可執(zhí)行文件
https://graphviz.gitlab.io/_pages/Download/Download_windows.html
Note: These Visual Studio packages do not alter the PATH variable or access the registry at all. If you wish to use the command-line interface to Graphviz or are using some other program that calls a Graphviz program, you will need to set the PATH variable yourself.
然后添加PATH路徑
重新執(zhí)行上面的代碼赘淮,成功了,不過是用pdf閱讀軟件打開的澄阳,如果使用的是Anaconda拥知,可以用Spyder或Jupyter notebook直接再打一個(gè)dot
就可以顯示
快速繪制
不要忘了我們用這個(gè)工具的原因是Visio用起來比較麻煩,所以如果這個(gè)工具畫的速度比較慢就失去了用它的意義碎赢。
- 對(duì)于只用一次的節(jié)點(diǎn)可以直接用label來描述,需要重用的則使用縮略id
from graphviz import Digraph
dot=Digraph()
#因?yàn)镚raph這個(gè)節(jié)點(diǎn)在后面和別的點(diǎn)連接的比較多速梗,所以簡寫為g
#下面這句話實(shí)際是dot.node("g",label="Graph")
dot.node("g","Graph")
#不用簡寫的直接采用label來表示
dot.edge("Session","g")
dot.edge("g","Placeholder")
dot.edge("g","Variable")
dot
- 如果覺得以上構(gòu)建節(jié)點(diǎn)和邊的方式還是太麻煩肮塞,我們可以使用DOT語言直接繪制,詳細(xì)的使用方法可以參考https://www.tuicool.com/articles/vy2Ajyu 以及 https://jingyan.baidu.com/article/19020a0a72f757529c284257.html
from graphviz import Source
code2="""graph
graphname{
rankdir=LR; //Rank Direction Left to Right
a[label="node1"];
a -- node2;
}"""
t=Source(code2)
t
例子
下面我們來大致(是真的很大致…)還原一下這個(gè)
from graphviz import Graph
#排列方式設(shè)定為環(huán)形
g=Graph(engine="circo")
#節(jié)點(diǎn)1為白色
g.node("1",shape="circle",color="white")
for i in range(2,8):
#第二層節(jié)點(diǎn)為紅色
g.node("%d"%i,shape="circle",color="red")
#第三層為默認(rèn)顏色
a=2*(i-2)+8
b=2*(i-2)+9
g.node("%d"%a,shape="circle")
g.node("%d"%b,shape="circle")
#添加第二層到第三層的邊
g.edge("1","%d"%i)
#添加第三層到第二層的邊
g.edge("%d"%a,"%d"%i)
g.edge("%d"%b,"%d"%i)
#添加
g.node("last",shape="box")
g.node("tail",shape="box")
g.edge("last","7")
g.edge("tail","17")
g
雖然可以通過方向控制符(n,ne,e,se,s,sw,w,nw)指定一條邊從起點(diǎn)的哪個(gè)位置射出和從哪個(gè)位置結(jié)束姻锁,但是這對(duì)上圖來說還是太麻煩了…看樣子枕赵,這種需要關(guān)注于繪制方式的圖,它還不太適合呢位隶。