Visualize a network with NetworkX using force-directed Fruchterman-Reingold layout. Calculate node positions where edges act as springs and nodes repel like magnets. Animate the layout convergence step by step.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The user wants Python code to visualize a network with NetworkX using the force-directed Fruchterman-Reingold layout and animate the step-by-step convergence showing forces as springs and repulsion. I've prepared a concise example that iteratively computes positions using NetworkX’s spring_layout with one iteration per frame, capturing intermediate layouts, and animates the node and edge movements with Matplotlib's FuncAnimation. This directly visualizes the layout evolving under the algorithm’s simulated forces.
Below is a minimal example in Python that:
Builds a simple graph with NetworkX.
Computes Fruchterman–Reingold (spring) positions one iteration at a time so we can see each step.
Animates the convergence using Matplotlib’s FuncAnimation.
python
import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
# 1) Build a small graph for demonstration
G = nx.erdos_renyi_graph(n=15, p=0.15, seed=1)
# 2) Collect layout positions over many iterations
# Start from a random initial layout (iterations=0 so it doesn't move yet)
pos = nx.spring_layout(G, iterations=0, seed=1)
pos_history = [pos.copy()]
num_steps = 50 # how many times we refine the layout
for i in range(num_steps):
# each call with iterations=1 advances the Fruchterman–Reingold
# algorithm by one step, starting from the previous positions
pos = nx.spring_layout(G, pos=pos, iterations=1)
pos_history.append(pos.copy())
# 3) Animate the positions with Matplotlib
fig, ax = plt.subplots(figsize=(6, 6))
ax.set_title("Fruchterman–Reingold Layout Convergence")
ax.set_xticks([])
ax.set_yticks([])
# Draw initial edges and nodes
edge_collection = nx.draw_networkx_edges(G, pos_history[0], ax=ax, edge_color='gray', alpha=0.7)
node_collection = ax.scatter([], [], s=300, c='dodgerblue', edgecolors='k', zorder=2)
def init():
# Set an initial view; values are broad enough to contain all positions
ax.set_xlim(-1.2, 1.2)
ax.set_ylim(-1.2, 1.2)
return node_collection, edge_collection
def update(frame):
pos = pos_history[frame]
# Update node coordinates
node_collection.set_offsets(np.array(list(pos.values())))
# Update edge line segments
segments = [ [pos[u], pos[v]] for u, v in G.edges() ]
edge_collection.set_segments(segments)
ax.set_title(f"Iteration {frame}")
return node_collection, edge_collection
ani = FuncAnimation(
fig,
update,
frames=len(pos_history),
init_func=init,
blit=True,
interval=100, # milliseconds between frames
repeat=False
)
plt.tight_layout()
plt.show()
How it works:
The Fruchterman–Reingold algorithm treats edges as springs (pulling their endpoints together) and nodes as electrically charged particles (repelling each other).
Calling nx.spring_layout(G, pos=..., iterations=1) advances the simulation by one iteration, starting from the previous positions.
Storing those positions in pos_history lets us animate the convergence process by updating node/edge coordinates frame by frame.
You can tweak num_steps, the graph size, and the animation interval to see how quickly (or slowly) the layout stabilizes.