Search code examples
pythonnetworkx

networkx draw nodes on a line in order with curved edges


I would like to draw a set of nodes on a line with spaces in between that correspond to the difference in a node property (here: the time when the node entered the system). I would then like to draw curved edges between these nodes. Is this possible in networkx?

I have attached a sketch of the layout that I would like to achieve.enter image description here


Solution

  • You can control the position of your nodes by passing a dictionary of the positions (x,y) of your nodes to the nx.draw function (see doc here). To add a curve to your arrows, you can use connectionstyle=’arc3,rad=-0.7’ (with rad taking whatever value you want for the curve) in the nx.draw function (see doc here).

    See example below:

    import networkx as nx
    import matplotlib.pyplot as plt
    
    G=nx.DiGraph()
    N_nodes=7
    
    [G.add_node(i) for i in range(N_nodes)]
    
    G.add_edge(0,1)
    G.add_edge(2,4)
    G.add_edge(2,5)
    
    posx=[0,1,3,5,6,7,9]
    posy=N_nodes*[0]
    pos={i:[posx[i],posy[i]] for i in range(N_nodes)}
    
    nx.draw(G,pos=pos,connectionstyle="arc3,rad=-0.7",edge_color='blue')
    plt.ylim([-0.5,0.5])
    

    enter image description here