Can one get hierarchical graphs from networkx with python 3?
Question: I am trying to display a tree graph of my class hierarchy using
**`networkx.`** I have it all graphed correctly, and it displays _fine_. But
as a circular graph with crossing edges, it is a pure hierarchy, and it seems
I ought to be able to display it as a tree.

I have googled this extensively, and every solution offered involves using
**`pygraphviz`**... but **_PyGraphviz does not work with Python 3
(documentation from the pygraphviz site)_**.

Has anyone been able to get a tree graph display in Python 3?


Answer: Here is a simple recursive program to define the positions:

    
    
    import networkx as nx
    
    def hierarchy_pos(G, root, width=1., vert_gap = 0.2, vert_loc = 0, xcenter = 0.5, 
                      pos = None, parent = None):
        '''If there is a cycle that is reachable from root, then this will see infinite recursion.
           G: the graph
           root: the root node of current branch
           width: horizontal space allocated for this branch - avoids overlap with other branches
           vert_gap: gap between levels of hierarchy
           vert_loc: vertical location of root
           xcenter: horizontal location of root
           pos: a dict saying where all nodes go if they have been assigned
           parent: parent of this branch.'''
        if pos == None:
            pos = {root:(xcenter,vert_loc)}
        else:
            pos[root] = (xcenter, vert_loc)
        neighbors = G.neighbors(root)
        if parent != None:
            neighbors.remove(parent)
        if len(neighbors)!=0:
            dx = width/len(neighbors) 
            nextx = xcenter - width/2 - dx/2
            for neighbor in neighbors:
                nextx += dx
                pos = hierarchy_pos(G,neighbor, width = dx, vert_gap = vert_gap, 
                                    vert_loc = vert_loc-vert_gap, xcenter=nextx, pos=pos, 
                                    parent = root)
        return pos
    

and an example usage:

    
    
    G=nx.Graph()
    G.add_edges_from([(1,2), (1,3), (1,4), (2,5), (2,6), (2,7), (3,8), (3,9), (4,10),
                      (5,11), (5,12), (6,13)])
    pos = hierarchy_pos(G,1)    
    nx.draw(G, pos=pos, with_labels=True)
    py.savefig('hierarchy.png')
    

![enter image description here](http://i.stack.imgur.com/kUTHb.png)

Ideally this should rescale the horizontal separation based on how wide things
will be beneath it. I'm not attempting that now.

