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

Shankar picture Shankar · Mar 17, 2013 · Viewed 7.9k times · Source
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.

Answer

Martijn Pieters picture Martijn Pieters · Mar 17, 2013

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.