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.
This is a great request for visualizing network layout using NetworkX with Fruchterman-Reingold algorithm and animating the convergence. Let me break down what needs to be done:
Create a network with NetworkX
Use the Fruchterman-Reingold force-directed layout algorithm
Calculate node positions step by step (showing convergence)
Animate the process
Visualize it with matplotlib
I'll create a comprehensive example that:
Generates a sample network
Implements or uses the FR algorithm with step-by-step updates
Creates an animation showing how nodes converge to their final positions
Shows the spring forces and repulsive forces visually
Provides multiple visualization options
Let me write a complete solution with multiple approaches and good explanations.
NetworkX Force-Directed Layout Animation with Fruchterman-Reingold
I'll create a comprehensive visualization with step-by-step convergence animation:
1. Basic Force-Directed Layout with Animation
python
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
from matplotlib.patches import FancyArrowPatch
from matplotlib.patches import Circle
import seaborn as sns
# Create a sample network
def create_sample_network():
"""Create an interesting network for visualization"""
G = nx.Graph()
# Add edges to create clusters
edges = [
# Cluster 1
(0, 1), (0, 2), (1, 2), (1, 3), (2, 3),
# Cluster 2
(4, 5), (4, 6), (5, 6), (5, 7), (6, 7), (7, 4),
# Cluster 3
(8, 9), (8, 10), (9, 10), (10, 11),
# Bridge edges
(3, 4), (7, 8), (11, 0)
]
G.add_edges_from(edges)
return G
# Create network
G = create_sample_network()
print(f"Network created with {G.number_of_nodes()} nodes and {G.number_of_edges()} edges")
# Calculate positions step by step using FR layout
pos_sequence = []
iterations = 50
# Use NetworkX FR algorithm with increasing iterations
for i in range(1, iterations + 1):
pos = nx.spring_layout(
G,
iterations=i,
seed=42,
k=0.5, # Optimal distance between nodes
scale=2
)
pos_sequence.append(pos.copy())
# Create animation
fig, ax = plt.subplots(figsize=(12, 10))
def animate(frame):
ax.clear()
pos = pos_sequence[frame]
# Draw edges
nx.draw_networkx_edges(
G, pos,
ax=ax,
width=1.5,
alpha=0.6,
edge_color='gray'
)
# Draw nodes with size based on degree
node_sizes = [500 + 100 * G.degree(node) for node in G.nodes()]
nodes = nx.draw_networkx_nodes(
G, pos,
ax=ax,
node_size=node_sizes,
node_color=range(G.number_of_nodes()),
cmap='twilight',
alpha=0.8,
edgecolors='black',
linewidths=2
)
# Draw labels
nx.draw_networkx_labels(
G, pos,
ax=ax,
font_size=9,
font_weight='bold'
)
ax.set_title(
f'Force-Directed Layout - Fruchterman-Reingold\n'
f'Iteration: {frame + 1}/{iterations}',
fontsize=14,
fontweight='bold'
)
ax.axis('off')
ax.set_aspect('equal')
# Create animation
anim = animation.FuncAnimation(
fig, animate,
frames=iterations,
interval=100,
repeat=True,
repeat_delay=2000
)
plt.tight_layout()
plt.savefig('network_animation.png', dpi=150, bbox_inches='tight')
print("Animation frames ready!")
# anim.save('network_convergence.gif', writer='pillow', fps=10)
plt.show()
2. Detailed Force Visualization (Physics-Based)
python
3. Interactive Convergence Visualization
python
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider
# Create network
G = create_sample_network()
# Generate positions at different iterations
pos_data = {}
iterations_list = [1, 5, 10, 20, 50, 100]
for it in iterations_list:
pos_data[it] = nx.spring_layout(G, iterations=it, seed=42, k=0.5)
# Create figure with subplots
fig, axes = plt.subplots(2, 3, figsize=(16, 10))
axes = axes.flatten()
for idx, iterations in enumerate(iterations_list):
ax = axes[idx]
pos = pos_data[iterations]
# Draw edges
nx.draw_networkx_edges(
G, pos,
ax=ax,
width=1.5,
alpha=0.5,
edge_color='gray'
)
# Draw nodes
node_sizes = [300 + 50 * G.degree(node) for node in G.nodes()]
nx.draw_networkx_nodes(
G, pos,
ax=ax,
node_size=node_sizes,
node_color='lightblue',
alpha=0.8,
edgecolors='black',
linewidths=2
)
# Draw labels
nx.draw_networkx_labels(G, pos, ax=ax, font_size=8)
ax.set_title(f'Iterations: {iterations}', fontsize=12, fontweight='bold')
ax.axis('off')
ax.set_aspect('equal')
plt.suptitle(
'Fruchterman-Reingold Layout Convergence',
fontsize=16,
fontweight='bold',
y=0.98
)
plt.tight_layout()
plt.savefig('convergence_comparison.png', dpi=150, bbox_inches='tight')
plt.show()