Sunday, December 17, 2006

Pydot: A Graphviz Wrapper

If you haven't played with any of Ero Carrera's python modules you should start. His wrappers for libdasm and graphviz are a lot of fun to mess around with. A few weeks back before I'd messed up my blog, I posted a few quick pictures made by my linkgraph.py. linkgraph.py in the form posted only graphs hrefs but does not follow the links. While writing linkgraph I noticed that the usage examples were a little sparse so here's a few pointers on how to use the module.



For really simple graphs use the graph from edges method as shown in Ero's usage docs.




import pydot

edges=[(1,2), (1,3), (1,4), (3,4)]
g=pydot.graph_from_edges(edges)
g.write_jpeg('graph_from_edges_dot.jpg', prog='dot')


If you want to label edges or add extra attributes to nodes and edges. Try the following.




import pydot

g = pydot.Dot(type='digraph')
g.add_node(pydot.Node('A',shape='ellipse',color='blue')) # add a node
g.add_node(pydot.Node('B'))
g.add_edge(pydot.Edge('A','B',label='A TO B'))
g.write_jpg('test.jpg')


This yields:





Notice the outline's changed and that my label appears on the edge



The important, yet kinda obvious thing to remember is that you add nodes to a graph and edges linking each node by name (the string value you gave each node) to a graph. Okay so I didn't add that much more but I think Ero's API docs may make more sense now :).

0 comments: