Is there a way to guarantee hierarchical output from NetworkX?

Viewed 61465

I'm trying to produce a flow diagram of a tree structure. I've been able to create representative graphs with networkx, but I need a way to show the tree structure when I output a plot. I'm using matplotlib.pylab to plot the graph.

I need to show the data in a structure similar to what is shown here. Although I don't have sub-graphs.

How can I guarantee a structure like that?

Examples for the unbelievers:

Various NetworkX layouts

I've been able to show the graphs with pylab and graphviz, but neither offer the tree structure I'm looking for. I've tried every layout networkx has to offer, but none of them show a hierarchy. I've just not sure what options/mode to give it OR if I need to use weights. Any suggestions would help a bunch.

@jterrace:

Here's a rough outline of what I used to produce the plots above. I've added some labels, but other than that it's the same.

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()

G.add_node("ROOT")

for i in xrange(5):
    G.add_node("Child_%i" % i)
    G.add_node("Grandchild_%i" % i)
    G.add_node("Greatgrandchild_%i" % i)

    G.add_edge("ROOT", "Child_%i" % i)
    G.add_edge("Child_%i" % i, "Grandchild_%i" % i)
    G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i)

plt.title("draw_networkx")
nx.draw_networkx(G)

plt.show()
5 Answers

You could do it manually just with only networkx. Traverse tree and for each children coordinate x change as if right parent.x+1/np.log(y_coord + 1) if left parent.x-1... and y = parent.y - 1 Or any other algorithm to get coord and eg. See image here.

import networkx as nx
import matplotlib.pyplot as plt
coord = {0: [8, 0], 2: [9, -1], 1: [8, -2], 4: [10, -2], 3: [9, -3], 5: [11, -3]}
eg = [[0, 2], [2, 1], [2, 4], [4, 3], [4, 5]]
G=nx.Graph()
G.add_edges_from(eg) 
nx.draw(G, with_labels=True, node_size=1500, node_color="skyblue", pos=coord) 
plt.show()
Related