NetworkX: How do I iteratively apply a network layout like spring_layout?
<p>I have a graph <code>G</code> and I want to layout the graph using the function </p>

<p><code>node_positions=nx.spring_layout(G, iterations=5)</code></p>

<p>However, I want to apply this function say 10 times and see how the layout changes with each application. Seems like every time I apply it, it starts from scratch giving me 10 layouts with 5 iterations each.</p>

<p>What I tried so far:</p>

<pre><code>for i in range(10):
    node_positions=nx.spring_layout(G, iterations=5)            
    nx.set_node_attributes(G,'pos',node_positions)

    # draw network    
    plt.figure()
    ns = nx.draw_networkx_nodes(G, pos=node_positions, node_color=node_colors, cmap = cm.PuRd, vmin=0, vmax = 0.035, node_size=70, alpha=.9)
    es = nx.draw_networkx_edges(G, pos=node_positions, alpha=.2, edge_color='#1a1a1a')

    plt.axis('off')
    plt.show()
</code></pre>

<p>I'd like to see how the spring layout works by visualizing its results every 5 iterations. Is there a way to achieve this? Thanks!</p>

<p><code>spring_layout</code> takes an argument <code>pos</code> which serves as the initial condition.</p>

<p>So <code>pos = nx.spring_layout(G, pos= pos, iterations=5)</code> will work.  For the first time through, just set <code>pos=None</code>.</p>

python graph networkx