pythonnetworkx

NetworkX: getting arrows/edges to point right


Is there a way to re-write my code at the end so that the graph it produces looks like this

enter image description here

Instead of like this

enter image description here

As a bonus, would anyone also know how to put in text labels above the nodes like in the 1st photo?

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_edges_from([(1, 2), (1, 3), (2, 4), (2, 5), (3, 6), (4, 7), (5, 7), (3, 8), (5, 8), (7, 9), (8, 9), (6, 10), (9, 10)])

pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_size=500)
nx.draw_networkx_edges(G, pos, edgelist=G.edges())
nx.draw_networkx_labels(G, pos)

plt.show()

Solution

  • You can use the graphviz layout with the dot program to get pretty close:

    pos=nx.drawing.nx_agraph.graphviz_layout(G, prog='dot', args='-Grankdir=LR')
    

    This will result in the following plot: Using graphviz layout

    If you want the rankings to match, it gets a little more complicated. Using this answer, you can do something like this:

    A = nx.nx_agraph.to_agraph(G)
    A.add_subgraph([2,3], rank='same')
    A.add_subgraph([4,5], rank='same')
    A.add_subgraph([7,8,6], rank='same')
    with open('my_graph.png', 'wb') as f:
        f.write(A.draw(prog='dot', format='png', args='-Grankdir=LR'))
    

    This results in:

    Using subgraph ranking