一、graphviz安装及配置
graphviz实际上是一个绘图工具,可以根据dot脚本画出树形图等。
1、windows安装
- 安装graphviz软件:https://graphviz.gitlab.io/_pages/download/download_windows.html
- 配置环境变量:把bin文件夹的路径加入到环境变量path里
- 安装python的graphviz模块:pip install graphviz
2、linux centos7安装
- yum下载graphviz软件:yum -y install graphviz
- 安装python的graphviz模块:pip install graphviz
- 测试: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")