我想绘制一个动态网络图,展示随着新观测数据的加入,它如何随时间变化。
我已经找到了如何在给定两个单一状态(此处称为s_pos,t_pos)的情况下对网络进行动画处理的方法,但我正在寻找更进一步的内容,因为我想逐行填充我的网络。
我想象中需要通过在anim(t)函数内遍历我的数据帧来更新G;但我很难做到这一点。
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# data
df = pd.DataFrame({'Date': ["2022-11-28", "2022-11-29", "2022-11-30", "2022-12-01"],
'ID' : ['A', 'B', 'C', 'A'],
'Value': ['X', 'Y', 'X', 'Z']})
# network
G = nx.from_pandas_edgelist(df, source='ID', target='Value')
# two states as an example
s_pos = nx.spring_layout(G)
t_pos = nx.circular_layout(G)
fig = plt.figure(figsize=(8, 8))
# animation function with smooth interpolation between states
def anim(t):
global s_pos
global t_pos
interpolation = {i: s_pos[i]*(1-t/299) + t_pos[i] * t/299 for i in list(t_pos.keys())}
plt.clf()
plt.cla()
nx.draw(G, pos=interpolation,
with_labels=True,
node_size = 5000)
# run and save
ani = animation.FuncAnimation(fig, anim, repeat=False, frames=300, interval=20)
f = r'path\network.gif'
writergif = animation.PillowWriter(fps=30)
ani.save(f, writer=writergif)