Python图论绘制库Graphviz小记

disorder

话不多说直接上代码,重要的都在注释里.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from graphviz import Digraph
from graphviz import Graph

# 有向图 g = Digraph(name="photo",format="png")

# 无向图
# name 是名称
# format 是导出文件的格式,默认是pdf
g = Graph(name="photo")

# name 是结点的变量名
# label 是显示时候结点的名称,也就是说可以创建两个"同名"结点
# color 是描边颜色

g.node(name='b1', label='2',color='black')
g.node(name='a',label='2', color='black')
g.node(name='b',label='5', color='black')

# 创建一条边,连接a与b
# label 为线上显示的文本
# color为线的颜色
g.edge('b1','a',label="",color="red")
g.edge('b1','b',label="",color="black")

g.node(name='c', label='6')
g.node(name='d', label='5')
g.edge('b','c',color="black")
g.edge('b','d',color="red")

g.node(name='e',label='2')
g.node(name='f',label='3')
g.edge('a','e',color="red")
g.edge('a','f',color="black")

g.node(name='g',label='7')
g.node(name='h',label='2')
g.edge('e','g',color="black")
g.edge('e','h',color="red")

g.node(name='i',label='3')
g.node(name='j',label='4')
g.edge('f','i',color="red")
g.edge('f','j',color="black")

g.node(name='k',label='6')
g.node(name='l',label='10')
g.edge('c','k',color="red")
g.edge('c','l',color="black")

g.node(name='m',label='8')
g.node(name='n',label='5')
g.edge('d','n',color="red")
g.edge('d','m',color="black")

# 显示图像 g.view()
# g.view()

# 画图,filename:图片的名称,若无filename,则使用Digraph对象的name,默认会有gv后缀
# directory:图片保存的路径,默认是在当前路径下保存
g.view(filename="mypicture", directory="/home/scheng")

运行后产生的图片文件 tournament-tree

更多详细内容可以参见

地址1

地址2