2013-03-16 32 views
1
import pygraphviz as pgv 
A = pgv.AGraph() 
A.add_node('Alice') 
A.add_node('Emma') 
A.add_node('John') 
A.add_edge('Alice', 'Emma') 
A.add_edge('Alice', 'John') 
A.add_edge('Emma', 'John') 
print A.string() 
print "Wrote simple.dot" 
A.write('simple.dot') # write to simple.dot 
B = pgv.AGraph('simple.dot') # create a new graph from file 
B.layout() # layout with default (neato) 
B.draw('simple.png') # draw png 
print 'Wrote simple.png' 

我想添加权重的边缘,这也应该显示在图上。如何使用PyGraphviz在无向图的边上添加和显示权重?

回答

5

当你创建它们,您可以将属性添加到边缘:

A.add_edge('Alice', 'Emma', weight=5) 

,或者您可以在以后将它们设置:

edge = A.get_edge('Alice', 'Emma') 
edge.attr['weight'] = 5 

为文本信息添加到边,给他们一个label属性代替:

edge = A.get_edge('Alice', 'Emma') 
edge.attr['label'] = '5' 

所有属性在内部存储为字符串,但GraphViz将它们解释为特定的类型;请参阅attribute documentation

+0

好了,重量改变了边缘的长度。但有没有办法显示图像边缘附近的权重? – Shankar 2013-03-16 23:55:09

+0

给他们一个明确的标签:'edge.attr ['label'] ='5'' – 2013-03-17 00:01:12

+1

您可能想参考GraphViz文档本身来查看[支持哪些属性](http://www.graphviz.org /doc/info/attrs.html)。 – 2013-03-17 00:07:58

相关问题