python graphviz的使用,,参考文章1参考文章2


参考文章1

参考文章2

一、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 YaHei1、字体样式华文黑体:STHeiti2、字体样式华文楷体:STKaiti3、字体样式华文宋体:STSong4、字体样式华文仿宋:STFangsong5、字体样式黑体:SimHei6、字体样式宋体:SimSun7、字体样式新宋体:NSimSun8、字体样式仿宋:FangSong9、字体样式楷体:KaiTi10、字体样式仿宋_GB2312:FangSong_GB231211、字体样式楷体_GB2312:KaiTi_GB231212、字体样式微软正黑体:Microsoft JhengHei13、字体样式微软雅黑体:Microsoft YaHei14、字体样式隶书:LiSu15、字体样式幼圆:YouYuan16、字体样式华文细黑:STXihei17、字体样式华文楷体:STKaiti18、字体样式华文宋体:STSong19、字体样式华文中宋:STZhongsong20、字体样式华文仿宋:STFangsong21、字体样式方正舒体:FZShuTi22、字体样式方正姚体:FZYaoti23、字体样式华文彩云:STCaiyun24、字体样式华文琥珀:STHupo25、字体样式华文隶书:STLiti26、字体样式华文行楷:STXingkai27、字体样式华文新魏:STXinwei
字体样式

from graphviz import Digraphdot = 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节点属性如下

NameDefaultValues
colorblacknode shape color
commentany string (format-dependent)
distortion0.0node distortion for shape=polygon
fillcolorlightgrey/blacknode fill color
fixedsizefalselabel text has no affect on node size
fontcolorblacktype face color
fontnameTimes-Romanfont family
fontsize14point size of label
groupname of node’s group
height.5height in inches
labelnode nameany string
layeroverlay rangeall, id or id:id
orientation0.0node rotation angle
peripheriesshape-dependentnumber of node boundaries
regularfalseforce polygon to be regular
shapeellipsenode shape; see Section 2.1 and Appendix E
shapefileexternal EPSF or SVG custom shape file
sides4number of sides for shape=polygon
skew0.0skewing of node for shape=polygon
stylegraphics options, e.g. bold, dotted, filled; cf. Section 2.3
URLURL associated with node (format-dependent)
width.75width in inches
z0.0z coordinate for VRML output

edge边框属性

NameDefaultValues
arrowheadnormalstyle of arrowhead at head end
arrowsize1.0scaling factor for arrowheads
arrowtailnormalstyle of arrowhead at tail end
colorblackedge stroke color
commentany string (format-dependent)
constrainttrueuse edge to affect node ranking
decorateif set, draws a line connecting labels with their edges
dirforwardforward, back, both, or none
fontcolorblacktype face color
fontnameTimes-Romanfont family
fontsize14point size of label
headlabellabel placed near head of edge
headportn,ne,e,se,s,sw,w,nw
headURLURL attached to head label if output format is ismap
labeledge label
labelangle-25.0angle in degrees which head or tail label is rotated off edge
labeldistance1.0scaling factor for distance of head or tail label from node
labelfloatfalselessen constraints on edge label placement
labelfontcolorblacktype face color for head and tail labels
labelfontnameTimes-Romanfont family for head and tail labels
labelfontsize14point size for head and tail labels
layeroverlay rangeall, id or id:id
lheadname of cluster to use as head of edge
ltailname of cluster to use as tail of edge
minlen1minimum rank distance between head and tail
sameheadtag for head node; edge heads with the same tag are
sametailmerged onto the same port
styletag for tail node; edge tails with the same tag are merged onto the same port
taillabelgraphics options, e.g. bold, dotted, filled; cf. Section 2.3
tailportlabel placed near tail of edge n,ne,e,se,s,sw,w,nw
tailURLURL attached to tail label if output format is ismap
weight1integer cost of stretching an edge

Digraph图属性如下

NameDefaultValues
bgcolorbackground color for drawing, plus initial fill color
centerfalsecenter drawing on page
clusterranklocalmay be global or none
colorblackfor clusters, outline color, and fill color if fillcolor not defined
commentany string (format-dependent)
compoundfalseallow edges between clusters
concentratefalseenables edge concentrators
fillcolorblackcluster fill color
fontcolorblacktype face color
fontnameTimes-Romanfont family
fontpathlist of directories to search for fonts
fontsize14point size of label
labelany string
labeljustcentered”l” and ”r” for left- and right-justified cluster labels, respectively
labelloctop”t” and ”b” for top- and bottom-justified cluster labels, respectively
layersid:id:id…
margin.5margin included in page, inches
mclimit1.0scale factor for mincross iterations
nodesep.25separation between nodes, in inches.
nslimitif set to f, bounds network simplex iterations by (f)(number of nodes) when setting x-coordinates
nslimit1if set to f, bounds network simplex iterations by (f)(number of nodes) when ranking nodes
orderingif out out edge order is preserved
orientationportraitif rotate is not used and the value is landscape, use landscape orientation
pageunit of pagination, e.g. “8.5,11”
pagedirBLtraversal order of pages
quantumif quantum ¿ 0.0, node label dimensions will be rounded to integral multiples of quantum
ranksame, min, max, source or sink
rankdirTBLR (left to right) or TB (top to bottom)
ranksep.75separation between ranks, in inches.
ratioapproximate aspect ratio desired, fill or auto
remincrossif true and there are multiple clusters, re-run crossing minimization
rotateIf 90, set orientation to landscape
samplepoints8number of points used to represent ellipses and circles on output (cf. Appendix C
searchsize30maximum edges with negative cut values to check when looking for a minimum one during network simplex
sizemaximum drawing size, in inches
stylegraphics options, e.g. filled for clusters
URLURL 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")

四、官网

官方文档

官网

python graphviz的使用

评论关闭