2
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'

我想为边缘添加权重,这些权重也应该显示在图中。

4

1 回答 1

9

您可以在创建边缘时向边缘添加属性:

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 将它们解释为特定类型;请参阅属性文档

于 2013-03-16T23:49:49.717 回答