Menu DaniWeb
Log In Sign Up
  • Read
  • Contribute
  • Meet
  1. Home
  2. Programming Forum
  3. Software Development Forum
  4. Code Snippet Repository
  5. Reusable Code Snippet

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

14 Years Ago Gribouillis 1 Tallied Votes 1K Views Share

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.

image python
mygraph.png 5.33 KB
# 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
About the Author
Member Avatar for Gribouillis
Gribouillis 1,391 Programming Explorer Team Colleague

Mind explorer.

Member Avatar for woooee
woooee 814 Nearly a Posting Maven
14 Years Ago

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

Reply to this topic
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Sign Up — It's Free!
Related Topics
  • Member Avatar Python PIL Tkinter image transparency. 3
  • Member Avatar Image from askopenfilename() not showing 3
  • Member Avatar help me... VectorBinaryTree 0
  • Member Avatar Creating a jpg file with Python 2
  • Member Avatar hey guys i have a big probe with my UNI assignment 5
  • Member Avatar Drawing a Christmas Tree with Python's Turtle Graphics 1
  • Member Avatar Name Backwards Algorithm 7
  • Member Avatar [Prob]Download image with python 2
  • Member Avatar access pc serial port thru c++ 2
  • Member Avatar PIL or equivalent for saving images in Python 3.x 7
  • Member Avatar Matrix Multiplication using Multi-Dimensional Arrays 12
  • Member Avatar Loading image from parent! 3
  • Member Avatar Changing XML content 3
  • Member Avatar trying to make my own text-based image file w/ compression and need help 0
  • Member Avatar How to make this code more efficient/clean-up? 2
  • Member Avatar 3d programming in Python 7
  • Member Avatar help plz with two dimensional array 3
  • Member Avatar grey scle textbased image + compression...your thoughts 1
  • Member Avatar NameError: name 'GraphWin' is not defined 1
  • Member Avatar simple picture and word game, help! 6
Not what you need?

Reach out to all the awesome people in our software development community by starting your own topic. We equally welcome both specific questions as well as open-ended discussions.

Start New Topic
Topics Feed
Reply to this Topic
Edit Preview

Share Post

Insert Code Block

  • Forums
  • Forum Index
  • Hardware/Software
    • Recommended Topics
  • Programming
    • Recommended Topics
  • Digital Media
    • Recommended Topics
  • Community Center
    • Recommended Topics
  • Latest Content
  • Newest Topics
  • Latest Topics
  • Latest Posts
  • Latest Comments
  • Top Tags
  • Topics Feed
  • Social
  • Top Members
  • Meet People
  • Community Functions
  • DaniWeb Premium
  • Newsletter Archive
  • Markdown Syntax
  • Community Rules
  • Developer APIs
  • Connect API
  • Forum API Docs
  • Tools
  • SEO Backlink Checker
  • Legal
  • Terms of Service
  • Privacy Policy
  • FAQ
  • About Us
  • Advertise
  • Contact Us
© 2025 DaniWeb® LLC