How to add and show weights on edges of a undirected graph using PyGraphviz?

北战南征 提交于 2019-12-21 21:09:23

问题


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'

I want to add weights to the edges which should also show up on the figure.


回答1:


You can add attributes to the edges when you create them:

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

or you can set them later with:

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

To add textual information to edges, give them a label attribute instead:

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

All attributes are internally stored as strings but GraphViz interprets these as specific types; see the attribute documentation.



来源:https://stackoverflow.com/questions/15455855/how-to-add-and-show-weights-on-edges-of-a-undirected-graph-using-pygraphviz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!