如何使用PyGraphviz在无向图的边缘上添加和显示权重?

时间:2013-03-16 23:17:48

标签: python python-2.7 graphviz pygraphviz

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'

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

1 个答案:

答案 0 :(得分:7)

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

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