如何在 Matplotlib 中使用更新函式對 NetworkX 圖形進行動畫化?
要使用更新函式對 Matplotlib 中的NetworkX圖形進行動畫化,我們可以採取以下步驟 -
- 設定圖形大小並調整子圖之間和周圍的填充。
- 使用figure()方法建立一個新圖形或啟用現有圖形。
- 使用邊、名稱和圖形屬性初始化圖形。
- 使用add_nodes_from()方法向圖形新增節點。
- 使用 Matplotlib 繪製圖形G。
- 使用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()
輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP