เพื่อใช้ฟังก์ชัน update ทำแอนิเมชันกราฟ NetworkX ใน Matplotlib ให้ทำตามขั้นตอน:
- กำหนดขนาดรูปและปรับระยะห่างระหว่างและรอบซับพล็อต
- สร้างรูปใหม่หรือเปิดใช้งานรูปที่มีอยู่ด้วย figure()
- เริ่มต้นกราฟด้วย edges, name, และ graph attributes
- เพิ่มโหนดด้วย add_nodes_from()
- วาดกราฟ G ด้วย Matplotlib
- ใช้คลาส FuncAnimation() สร้างแอนิเมชันโดยเรียกฟังก์ชัน animate ซ้ำ
- ฟังก์ชัน animate ล้างรูป สร้างเลขสุ่มสองตัว และวาดเส้นเชื่อมระหว่างกัน
- ใช้ show() เพื่อแสดงรูป
ตัวอย่าง
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()ผลลัพธ์
