
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 take the following steps −
- 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, animate.
- Function animate clears the current figure, generate two random numbers, and draws the edges between them.
- To display the figure, use show() method.
Example
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()
Output
- Related Articles
- How to change the attributes of a networkx / matplotlib graph drawing?
- Drawing a network graph with networkX and Matplotlib
- Animate a rotating 3D graph in Matplotlib
- How to reshape a networkx graph in Python?
- How to animate a pcolormesh in Matplotlib?
- How to draw node colormap in NetworkX/Matplotlib?
- How to animate text in Matplotlib?
- How to animate a scatter plot in Matplotlib?
- How to animate a sine curve in Matplotlib?
- How to animate a line plot in Matplotlib?
- How to set NetworkX edge labels offset in Matplotlib?
- How to animate the colorbar in Matplotlib?
- How to animate 3D plot_surface in Matplotlib?
- How to show node name in Matplotlib graphs using networkx?
- How to make multipartite graphs using networkx and Matplotlib?

Advertisements