Question

I have a graph in Networkx with different info inside. The graph nodes look like this:

G = nx.DiGraph()
G.add_node(shape1, level=1)
G.add_node(shape2, level=2)
G.add_node(shape3, level=2)
G.add_node(shape4, level=3)
...

I want to draw the graph in order to have all the shapes at level 1 at the top of the plot, all the shapes in level 3 positioned in the lower part of the plot and all the shapes at level 2 in the middle. There are maximum 3 levels.

I have been reading documentations from NetworkX, but till now I used only this random positioning of the nodes:

pos = nx.spring_layout(G) nx.draw(G, pos).

Do you know any smarter way to position the nodes of the graph as I want?

P.S.: The desired output would be roughly like this: enter image description here

I don't need to draw also the lines for dividing the levels, I just put them to make it clear what I need.

Était-ce utile?

La solution

The layout "dot" provided the interface to graphviz seems to do what you are looking for. While it works for this simple graph you've provided, you may need to tweak the output for larger more complicated graphs.

import networkx as nx

G = nx.DiGraph()
G.add_node(1,level=1)
G.add_node(2,level=2)
G.add_node(3,level=2)
G.add_node(4,level=3)

G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(2,4)

import pylab as plt
nx.draw_graphviz(G, node_size=1600, cmap=plt.cm.Blues,
                 node_color=range(len(G)),
                 prog='dot')
plt.show()

enter image description here

Autres conseils

Updated answer for NetworkX 2.6.2:

pos = nx.nx_pydot.graphviz_layout(G, prog="dot")
nx.draw(G, pos=pos, with_labels=True, font_weight='bold')
plt.show()

(make sure you have pydot installed)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top