Search code examples
pythonnetworkx

How to keep node positions when changing edges


Consider the following MWE with three commented lines:

import matplotlib.pyplot as plt
import networkx as nx
import pydot
from networkx.drawing.nx_pydot import graphviz_layout

T = nx.balanced_tree(2, 5)
# T.remove_edge(3,8)
# T.add_edge(3,4)
# T.add_edge(7,8)
for line in nx.generate_adjlist(T):
    print(line)
pos = graphviz_layout(T, prog="dot")
nx.draw(T, pos, node_color="y", edge_color='#909090', node_size=200, with_labels=True)

plt.show()

This produces:

enter image description here

I would like to be able to uncomment the lines but have all the nodes stay in the same place as above. Just the edges should change. How can you do that?


Solution

  • pos is just a dictionary that maps nodes to their positions. As long as you don't add any additional nodes, you can remove any nodes or edit any edges after calculating the positions and still use the same pos dict.

    Basically, just reorder your code:

    import matplotlib.pyplot as plt
    import networkx as nx
    import pydot
    from networkx.drawing.nx_pydot import graphviz_layout
    
    T = nx.balanced_tree(2, 5)
    
    for line in nx.generate_adjlist(T):
        print(line)
    pos = graphviz_layout(T, prog="dot")
    
    T.remove_edge(3,8) # moved this line
    T.add_edge(3,4) # moved this line
    T.add_edge(7,8) # moved this line
    
    nx.draw(T, pos, node_color="y", edge_color='#909090', node_size=200, with_labels=True)
    
    plt.show()
    

    giving

    network_same_pos_diff_edges