Python調用Graphviz畫流程圖

原文地址

分類目錄——萬能的Python系列

近來發現了一個神奇的畫流程圖的工具——Graphviz

Graphviz官網

什麼是Graphviz?

Graphviz是開源的圖形可視化軟件。圖形可視化是一種將結構信息表示爲抽象圖形和網絡圖的方式。它在網絡,生物信息學,軟件工程,數據庫和網頁設計,機器學習以及其他技術領域的可視界面中具有重要的應用。

簇

引自 Graphviz官網+谷歌翻譯

就是一個應用性很好的畫流程圖工具

Graphviz支持在文本文檔中寫語法命令行繪圖、支持在Markdown文檔中繪圖、也有相應的Python工具包通過編程繪圖

使用之前首先要在本地安裝,Windows下在 下載地址 下載壓縮包解壓即可使用

解壓之後爲了方便使用需要配置環境變量,將工具文件中的bin目錄(如我的是 C:\Program Files\graphviz\bin)添加到環境變量中,此時在命令行中就可以直接調用其命令了,但是我配置完環境變量緊接着在Pycharm中操作時新配置的環境變量並沒有生效,大概是需要重啓電腦的,我是在Pycharm中通過os模塊的命令又添加了一下環境變量

  • Python編程繪圖

    • 先看效果

      Graphviz_test
    • 導入支持包

      from graphviz import Digraph
      from graphviz import Source
      
    • 因爲環境變量不能即時生效配置環境變量

      import os
      os.environ["PATH"] += os.pathsep + r'C:\Program Files\graphviz\bin'
      
    • 創建圖對象

      dot = Digraph(
          name='Graphtest',
          comment='添加到源碼第一行的註釋',
          filename=None,
          directory=None,
          format="png",
          engine=None,
          encoding='utf8',
          graph_attr={'rankdir':'TB'},
          node_attr={'color':'black','fontcolor':'black','fontname':'FangSong','fontsize':'12','style':'rounded','shape':'box'},
          edge_attr={'color':'#999999','fontcolor':'#888888','fontsize':'10','fontname':'FangSong'},
          body=None,
          strict=False
      )
      

      其中

      • name: 圖的名字,打開時顯示的圖的名字.
      • comment: 添加的源碼第一行的註釋.
      • filename: 指定保存圖片時的文件名
      • directory: (Sub)directory for source saving and rendering.
      • format: 輸出圖片的格式 ('pdf', 'png', …).
      • engine: Layout command used ('dot', 'neato', …).
      • encoding: 圖的編碼方式,such as ‘utf8’.
      • graph_attr: 圖屬性,屬性字典的形式.
      • node_attr: 節點屬性,屬性字典的形式.
        shape可以是oval(橢圓)、circle(圓)、box(圓角矩形)。。。
      • edge_attr: 邊(連線)屬性,屬性字典的形式.
      • body: Iterable of verbatim lines to add to the graph body.
      • strict (bool): 如果設置了多條A->B,渲染時多條合併.

      其中node_attr、edge_attr中有fontname這樣一個屬性,用來指定字體,尤其繪圖中有中文的時候需要指定一個支持中文的字體(默認是不支持中文的)

    • 添加節點——dot.node()

      dot.node('A', 'this is A', {'shape':'circle','color':'blue','fontcolor':'blue'})
      # shape 節點形狀
      # color 顏色
      # fontcolor 字體顏色
      dot.node('B', 'this is B')
      dot.node('C', 'this is C')
      dot.node('D', 'this is D')
      dot.node('E', 'this is E')
      dot.node('F', 'this is F')
      

      在聲明Digraph()對象時也進行節點屬性的的指定,此時以這裏爲準,就近原則

    • 添加邊——dot.edge() dot.edges()

      dot.edge('A', 'B', 'test', _attributes={'style':'dotted', 'dir':'both'})
      # style 線的類型,實線,虛線等
      # dir   線(箭頭)的方向,單向、雙向等
      
      # 創建一堆邊,即連接AB的兩條邊,連接AC的一條邊。
      dot.edges(['AC', 'BD', 'BE', 'EF'])
      

      在聲明Digraph()對象時也進行邊屬性的的指定,此時以這裏爲準,就近原則

    • dot.其他

      dot.view()
      顯示圖,注意語句的位置,只顯示該句之前聲明的圖元素
      
      dot.source
      獲得該圖對應的文本語法(可以直接拷貝到Markdown中顯示,直接保存到文本文檔中可以調用命令行繪圖)
      
      dot.save(filename='source.gv', directory='data')
      # 保存源碼,可以指定文件名,文件名取 指定名>Digraph屬性中的filename>Digraph屬性中的name
      
      dot.render(directory='data') 
      # 保存圖片,可以指定文件名,文件名取 指定名>filename>name
      
      # 從保存的文件讀取並顯示
      dot_ = Source.from_file('data/source.gv')
      print(dot_.source)  # 打印文本如法如下
      # // 添加到源碼第一行的註釋
      # digraph Graphtest {
      # 	graph [rankdir=TB]
      # 	node [color=black fontcolor=black fontname=FangSong fontsize=12 shape=box style=rounded]
      # 	edge [color="#999999" fontcolor="#888888" fontname=FangSong fontsize=10]
      # 	A [label="this is A" color=blue fontcolor=blue shape=circle]
      # 	B [label="this is B"]
      # 	C [label="this is C"]
      # 	D [label="this is D"]
      # 	E [label="this is E"]
      # 	F [label="this is F"]
      # 	A -> B [label=test dir=both style=dotted]
      # 	A -> C
      # 	B -> D
      # 	B -> E
      # 	E -> F
      # }
      

      dot.view()效果如本節開頭所示

    • 依次複製代碼即可運行,更多Digraph、node、edge屬性參見 Node, Edge and Graph Attributes

  • 在Markdown文檔中

    語法

    ![testgraphviz](https://g.gravizo.com/svg?流程圖的定義語句)
    

    一個例子,取自 https://graphviztutorial.readthedocs.io/zh_CN/latest/chap01.html#id3

    ![testgraphviz](https://g.gravizo.com/svg?
    digraph G {
        main [shape=box];
        main -> parse [weight=8];
        parse-> execute;
        main -> init [style=dotted];
        main -> cleanup;
        execute -> {make_string, printf};
        init -> make_string;
        edge [color=red];
        main -> printf [style=bold, label="100 times"];
        make_string [label = "make a\nstring"];
        node [shape=box, style=filled,color=".7, .3, 1.0"];
        execute -> compare;
    })
    

    跟多繪圖語法可以搜索關鍵字 DOT語法

    效果

    ![testgraphviz](https://g.gravizo.com/svg?
    digraph G {
    main [shape=box];
    main -> parse [weight=8];
    parse-> execute;
    main -> init [style=dotted];
    main -> cleanup;
    execute -> {make_string, printf};
    init -> make_string;
    edge [color=red];
    main -> printf [style=bold, label=“100 times”];
    make_string [label = “make a\nstring”];
    node [shape=box, style=filled,color=".7, .3, 1.0"];
    execute -> compare;
    })

  • 文本文檔+命令行

    參見 Graphviz Tutorial 1.0 文檔,注意文件的後綴名要正確指定

    跟多繪圖語法可以搜索關鍵字 DOT語法

說明比較簡陋,僅拋磚引玉

參考文獻

Graphviz Tutorial 1.0 文檔

Node, Edge and Graph Attributes

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章