How to use an update function to animate a NetworkX graph in Matplotlib?

To use an update function to animate a NetworkX graph in Matplotlib, we can create dynamic visualizations where nodes and edges change over time. This is useful for visualizing network growth, data flow, or other time-based graph changes.

Steps to Animate NetworkX Graphs

  • Set the figure size and adjust the padding between and around the subplots
  • Create a new figure or activate an existing figure using figure() method
  • Initialize a graph with edges, name, and graph attributes
  • Add nodes to the graph using add_nodes_from() method
  • Draw the graph G with Matplotlib
  • Use FuncAnimation() class to make an animation by repeatedly calling a function
  • The animate function clears the current figure, generates random connections, and draws the updated graph
  • Display the figure using show() method

Example

Here's how to create an animated NetworkX graph that randomly adds edges over time −

from matplotlib import pyplot as plt, animation
import networkx as nx
import random

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()

G = nx.DiGraph()
G.add_nodes_from([0, 1, 2, 3, 4])

nx.draw(G, with_labels=True)

def animate(frame):
    fig.clear()
    num1 = random.randint(0, 4)
    num2 = random.randint(0, 4)
    G.add_edges_from([(num1, num2)])
    nx.draw(G, with_labels=True)

ani = animation.FuncAnimation(fig, animate, frames=6, interval=1000, repeat=True)

plt.show()

How the Animation Works

The FuncAnimation repeatedly calls the animate() function. Each time it runs −

  • fig.clear() removes the previous drawing
  • Two random numbers generate new node connections
  • G.add_edges_from() adds the new edge to the graph
  • nx.draw() redraws the updated graph with labels

Advanced Animation Example

Here's a more controlled animation that builds a graph step by step −

from matplotlib import pyplot as plt, animation
import networkx as nx

plt.rcParams["figure.figsize"] = [8.00, 6.00]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
G = nx.Graph()

# Predefined edges to add sequentially
edges_to_add = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2), (1, 3)]
current_edges = []

def animate(frame):
    fig.clear()
    
    if frame < len(edges_to_add):
        current_edges.append(edges_to_add[frame])
        G.clear()
        G.add_edges_from(current_edges)
    
    pos = nx.spring_layout(G, seed=42)  # Fixed layout
    nx.draw(G, pos, with_labels=True, node_color='lightblue', 
            node_size=500, font_size=16, font_weight='bold')
    
    plt.title(f"Graph Animation - Step {frame + 1}")

ani = animation.FuncAnimation(fig, animate, frames=len(edges_to_add), 
                            interval=1500, repeat=True)

plt.show()

Key Parameters

  • frames − Number of animation frames
  • interval − Delay between frames in milliseconds
  • repeat − Whether to loop the animation
  • spring_layout() − Provides consistent node positioning

Conclusion

NetworkX graph animation combines FuncAnimation with graph updates to create dynamic visualizations. Use fig.clear() and redraw for each frame, and consider fixed layouts for smoother animations.

Updated on: 2026-03-25T23:37:16+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements