1,105,271 Community Members

Link any objects in a graph, and draw the graph.

Member Avatar
Reputation Points: 1,140 [?]
Q&As Helped to Solve: 883 [?]
Skill Endorsements: 18 [?]
 
1
 

This snippet defines 3 functions to create in a few seconds an image of
a graph containing arbitrary python objects. It uses the module pygraphviz
(available at http://pypi.python.org/pypi/pygraphviz/).

See the example use case at the end of the module.

Attachments mygraph.png 5.33KB
# module fastgraph
# created by Gribouillis for the python forum at www.daniweb.com
# November 9, 2010
# Licence: public domain

"""This module defines 3 functions (node, edge and graph) to help
create a graph (a pygraphviz.AGraph instance) linking arbitrary
python objects.

This graph can be saved in various image formats, and in dot format.
"""

import pygraphviz

def node(x):
    "helper to create graphs"
    return (x,)

def edge(x, y):
    "helper to create graphs"
    return (x, y)

def graph(items, tolabel, **kwd):
    """Create a pygraphviz AGraph instance

    @ items - a sequence of node(obj), or edge(obj, obj) items (obj can be any python object)
    @ tolabel - a function tolabel(obj) -> str which converts an object to string
    @ **kwd - additional keyword arguments for AGraph.__init__
    """
    names = dict()
    the_graph = pygraphviz.AGraph(**kwd)
    for uple in (tuple(t) for t in items):
        for obj in uple:
            if not obj in names:
                names[obj] = "n%d" % len(names)
                the_graph.add_node(names[obj], label=tolabel(obj), shape="box")
        if len(uple) == 2:
            the_graph.add_edge(*(names[obj] for obj in uple))
    return the_graph

if __name__ == "__main__":
    
    def my_items():
        """Exemple generator of graph items. Our graph contains string here"""
        for x in "abcde":
            yield node(x)
        for s in "ab ac bd ea da".split():
            x, y = iter(s)
            yield edge(x, y)
            
    def my_label(x):
        "Create a label for graph objects"
        return x.upper()
    
    g = graph(my_items(), my_label)
    g.draw('mygraph.png', prog='circo') # prog can be neato|dot|twopi|circo|fdp|nop
Member Avatar
woooee
Posting Maven
2,792 posts since Dec 2006
Reputation Points: 783 [?]
Q&As Helped to Solve: 836 [?]
Skill Endorsements: 12 [?]
 
0
 

Consider posting this in the tutorials forum also so we can find it later
http://www.daniweb.com/tutorials/forum114.html

You
Post:
Start New Discussion
View similar articles that have also been tagged: