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


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

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

Attachments mygraph.png 5.33 KB
# module fastgraph
# created by Gribouillis for the python forum at
# 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
Isn't it about time forums rewarded their contributors?

Earn rewards points for helping others. Gain kudos. Cash out. Get better answers yourself.

It's as simple as contributing editorial or replying to discussions labeled or OP Kudos

This is an OP Kudos discussion and contributors may be rewarded
Start New Discussion
View similar articles that have also been tagged: