elgnoh
elgnoh

Reputation: 523

Fixed position hierarchical output from NetworkX without graphviz?

I'm trying to use Python to plot simple hierarchical tree. I'm using the networkx module. I declared a simple graph

G=networkx.DiGraph() 

After adding nodes and edges into G, I tried using

nx.draw(G) 

or

nx.draw_networkx(G) 

to plot. The output plot hierarchy are all correct, but the position of the nodes appears all random on the graph. Even worse, each time I ran the script, the node position are different.

There is a solution provided in a similar question which requires graphviz package.

pos=nx.graphviz_layout(G,prog='dot')
nx.draw(G,pos,with_labels=False,arrows=False)

Unfortunately I'm not allowed to install graphviz. So I'm seeking alternative solution here. From graphviz solution, it looks like it's only needed to compute position of the node. Is it correct to say that, as long as I specify a list of coordinates to the draw command, I would be able to plot node at the correct location?

Thanks

Upvotes: 3

Views: 3614

Answers (1)

Joel
Joel

Reputation: 23887

UPDATE (15 Apr 2015) Look at my answer here for code that I think will do what you're after.


So networkx doesn't make it particularly easy to use the graphviz layout if you don't have graphviz because it's a better idea to use graphviz's algorithm if you're trying to reproduce graphviz's layout.

But, if you're willing to put in the effort to calculate the position for each node this is straightforward (as you guessed). Create a dict saying where each node's position should be.

pos = {}
for node in G.nodes():
    pos[node] = (xcoord,ycoord)

nx.draw(G,pos)

will do it where xcoord and ycoord are the coordinates you want to have.

The various plotting commands are described here

Upvotes: 4

Related Questions