Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách dùng hàm update để tạo animation đồ thị NetworkX trong Matplotlib


Để tạo animation cho đồ thị NetworkX bằng Matplotlib, bạn sử dụng FuncAnimation gọi lại hàm animate định kỳ.

  • Thiết lập kích thước hình vẽ và khoảng đệm.
  • Tạo figure.
  • Khởi tạo đồ thị có hướng nx.DiGraph() và thêm các node.
  • Vẽ đồ thị ban đầu.
  • Định nghĩa hàm animate(frame): xóa figure, sinh ngẫu nhiên hai node, thêm cạnh, vẽ lại đồ thị.
  • Tạo animation.FuncAnimation với số khung hình và khoảng thời gian.
  • Hiển thị animation.

Ví dụ minh họa

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()

Kết quả đầu ra

Cách dùng hàm update để tạo animation đồ thị NetworkX trong Matplotlib