python graphviz的使用(畫圖工具)


參考文章1

參考文章2

一、graphviz安裝及配置

graphviz實際上是一個繪圖工具,可以根據dot腳本畫出樹形圖等。

 

1、windows安裝

  1. 安裝graphviz軟件:https://graphviz.gitlab.io/_pages/Download/Download_windows.html
  2. 配置環境變量:把bin文件夾的路徑加入到環境變量path里
  3. 安裝python的graphviz模塊:pip install graphviz

 

2、linux centos7安裝

  1. yum下載graphviz軟件:yum -y install graphviz
  2. 安裝python的graphviz模塊:pip install graphviz
  3. 測試:which dot

 

二、graphviz的使用

graphviz 有兩種圖,一種是無向圖 graph ,邊用 -- 連接,一種是有向圖 digraph ,邊用 -> 連接

1、初步認識

from graphviz import Digraph

# 實例化一個Digraph對象(有向圖),name:生成的圖片的圖片名,format:生成的圖片格式
dot = Digraph(name="MyPicture", comment="the test", format="png")

# 生成圖片節點,name:這個節點對象的名稱,label:節點名,color:畫節點的線的顏色
dot.node(name='a', label='Ming', color='green')
dot.node(name='b', label='Hong', color='yellow')
dot.node(name='c', label='Dong')

# 在節點之間畫線,label:線上顯示的文本,color:線的顏色
dot.edge('a', 'b', label="ab\na-b", color='red')
# 一次性畫多條線,c到b的線,a到c的線
dot.edges(['cb', 'ac'])

# 打印生成的源代碼
print(dot.source)

# 畫圖,filename:圖片的名稱,若無filename,則使用Digraph對象的name,默認會有gv后綴
# directory:圖片保存的路徑,默認是在當前路徑下保存
dot.view(filename="mypicture", directory="D:\MyTest")

# 跟view一樣的用法(render跟view選擇一個即可),一般用render生成圖片,不使用view=True,view=True用在調試的時候
dot.render(filename='MyPicture', directory="D:\MyTest",view=True)

使用node()和edge()或edges()方法將節點和邊添加到圖形對象:

  • Digraph():實例化一個圖形對象
  • node():方法第一個參數是name,第二個參數是label,即node畫節點
  • edges():方法可以一次添加多個邊, 每個邊用字符串表示, 比如 cb 表示從 c 到 b 的邊,即edges畫邊
  • edge():方法一次添加一個邊
  • view():把圖形畫出來,並自動顯示圖片(彈出來),一般使用view()進行調試
  • render():把圖形畫出來,一般使用render保存圖片的時候,view=False(不彈出圖片)

調試推薦使用 view()

保存圖片推薦使用 render(view=False)

 

2、字體亂碼

中文的label默認是無法正確顯示在圖中的, 因為默認的字體並不支持中文, 需要我們為node設置字體。

# 有些字體是需要下載的,默認使用Microsoft YaHei就好

0、字體樣式微軟雅黑:Microsoft YaHei

1、字體樣式華文黑體:STHeiti

2、字體樣式華文楷體:STKaiti

3、字體樣式華文宋體:STSong

4、字體樣式華文仿宋:STFangsong

5、字體樣式黑體:SimHei

6、字體樣式宋體:SimSun

7、字體樣式新宋體:NSimSun

8、字體樣式仿宋:FangSong

9、字體樣式楷體:KaiTi

10、字體樣式仿宋_GB2312:FangSong_GB2312

11、字體樣式楷體_GB2312:KaiTi_GB2312

12、字體樣式微軟正黑體:Microsoft JhengHei

13、字體樣式微軟雅黑體:Microsoft YaHei

14、字體樣式隸書:LiSu

15、字體樣式幼圓:YouYuan

16、字體樣式華文細黑:STXihei

17、字體樣式華文楷體:STKaiti

18、字體樣式華文宋體:STSong

19、字體樣式華文中宋:STZhongsong

20、字體樣式華文仿宋:STFangsong

21、字體樣式方正舒體:FZShuTi

22、字體樣式方正姚體:FZYaoti

23、字體樣式華文彩雲:STCaiyun

24、字體樣式華文琥珀:STHupo

25、字體樣式華文隸書:STLiti

26、字體樣式華文行楷:STXingkai

27、字體樣式華文新魏:STXinwei
字體樣式

 

from graphviz import Digraph

dot = Digraph(name="MyPicture", format="png")
dot.node(name="A", label="老師", fontname="Microsoft YaHei")
dot.node('B', '學生', fontname="Microsoft YaHei")
dot.edge("A", "B", label="教學", fontname="Microsoft YaHei")
dot.render(filename="MyPicture")

 

3、無向圖

用法跟有向圖一樣

from graphviz import Graph

# 無向圖
dot = Graph(name="MyPicture", format="png")

dot.node("People")
dot.node("Home")
dot.edge("People", "Home")
dot.view(filename="MyPicture")

 

三、屬性(樣式)說明

node節點屬性如下 

Name Default Values
color black node shape color
comment   any string (format-dependent)
distortion 0.0 node distortion for shape=polygon
fillcolor lightgrey/black node fill color
fixedsize false label text has no affect on node size
fontcolor black type face color
fontname Times-Roman font family
fontsize 14 point size of label
group   name of node’s group
height .5 height in inches
label node name any string
layer overlay range all, id or id:id
orientation 0.0 node rotation angle
peripheries shape-dependent number of node boundaries
regular false force polygon to be regular
shape ellipse node shape; see Section 2.1 and Appendix E
shapefile   external EPSF or SVG custom shape file
sides 4 number of sides for shape=polygon
skew 0.0 skewing of node for shape=polygon
style   graphics options, e.g. bold, dotted, filled; cf. Section 2.3
URL   URL associated with node (format-dependent)
width .75 width in inches
z 0.0 z coordinate for VRML output

 

edge邊框屬性

Name Default Values
arrowhead normal style of arrowhead at head end
arrowsize 1.0 scaling factor for arrowheads
arrowtail normal style of arrowhead at tail end
color black edge stroke color
comment   any string (format-dependent)
constraint true use edge to affect node ranking
decorate   if set, draws a line connecting labels with their edges
dir forward forward, back, both, or none
fontcolor black type face color
fontname Times-Roman font family
fontsize 14 point size of label
headlabel   label placed near head of edge
headport   n,ne,e,se,s,sw,w,nw
headURL   URL attached to head label if output format is ismap
label   edge label
labelangle -25.0 angle in degrees which head or tail label is rotated off edge
labeldistance 1.0 scaling factor for distance of head or tail label from node
labelfloat false lessen constraints on edge label placement
labelfontcolor black type face color for head and tail labels
labelfontname Times-Roman font family for head and tail labels
labelfontsize 14 point size for head and tail labels
layer overlay range all, id or id:id
lhead   name of cluster to use as head of edge
ltail   name of cluster to use as tail of edge
minlen 1 minimum rank distance between head and tail
samehead   tag for head node; edge heads with the same tag are
sametail   merged onto the same port
style   tag for tail node; edge tails with the same tag are merged onto the same port
taillabel   graphics options, e.g. bold, dotted, filled; cf. Section 2.3
tailport   label placed near tail of edge n,ne,e,se,s,sw,w,nw
tailURL   URL attached to tail label if output format is ismap
weight 1 integer cost of stretching an edge

 

Digraph圖屬性如下

Name Default Values
bgcolor   background color for drawing, plus initial fill color
center false center drawing on page
clusterrank local may be global or none
color black for clusters, outline color, and fill color if fillcolor not defined
comment   any string (format-dependent)
compound false allow edges between clusters
concentrate false enables edge concentrators
fillcolor black cluster fill color
fontcolor black type face color
fontname Times-Roman font family
fontpath   list of directories to search for fonts
fontsize 14 point size of label
label   any string
labeljust centered ”l” and ”r” for left- and right-justified cluster labels, respectively
labelloc top ”t” and ”b” for top- and bottom-justified cluster labels, respectively
layers   id:id:id…
margin .5 margin included in page, inches
mclimit 1.0 scale factor for mincross iterations
nodesep .25 separation between nodes, in inches.
nslimit   if set to f, bounds network simplex iterations by (f)(number of nodes) when setting x-coordinates
nslimit1   if set to f, bounds network simplex iterations by (f)(number of nodes) when ranking nodes
ordering   if out out edge order is preserved
orientation portrait if rotate is not used and the value is landscape, use landscape orientation
page   unit of pagination, e.g. “8.5,11”
pagedir BL traversal order of pages
quantum   if quantum ¿ 0.0, node label dimensions will be rounded to integral multiples of quantum
rank   same, min, max, source or sink
rankdir TB LR (left to right) or TB (top to bottom)
ranksep .75 separation between ranks, in inches.
ratio   approximate aspect ratio desired, fill or auto
remincross   if true and there are multiple clusters, re-run crossing minimization
rotate   If 90, set orientation to landscape
samplepoints 8 number of points used to represent ellipses and circles on output (cf. Appendix C
searchsize 30 maximum edges with negative cut values to check when looking for a minimum one during network simplex
size   maximum drawing size, in inches
style   graphics options, e.g. filled for clusters
URL   URL associated with graph (format-dependent)

 

例子

"""使用graph_attr, node_attr, edge_attr參數, 你可以更改圖中節點和邊的顯示樣式"""

from graphviz import Digraph

# 可以在實例化對象的時候設置樣式
dot = Digraph(name="MyPicture", node_attr={"shape": "plaintext"}, format="png")

# 也可以實例化之后, 設置這些樣式
dot.graph_attr['rankdir'] = 'LR'
dot.edge_attr.update(arrowhead='vee', arrowsize='2')

# 然后開始畫圖
dot.node("Dog")
dot.node("Cat")
dot.edge("Dog", "Cat")

dot.view(filename="MyPicture")

 

四、官網

官方文檔

官網

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM