动画网络图

3
我想绘制一个动态网络图,展示随着新观测数据的加入,它如何随时间变化。 我已经找到了如何在给定两个单一状态(此处称为s_post_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)
1个回答

0

如果我正确理解了您的问题,您想让您的网络逐行出现在动画中,一种方法是在anim函数中基于数据框的行创建一个新的网络Gt。在每个动画步骤中,您还可以使用ax.clear()清除绘图,就像这个post中所示。

请参见下面的示例:

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']})

G = nx.from_pandas_edgelist(df, source='ID', target='Value') # create full graph G for reference
s_pos = nx.spring_layout(G)
t_pos = nx.circular_layout(G)

fig,ax = plt.subplots(figsize=(8, 8))

# animation function with smooth interpolation between states
def anim(t):
    Gt=nx.from_pandas_edgelist(df.iloc[0:t], source='ID', target='Value') #create graph based n the row of the data frame up to t
    interpolation = {i: s_pos[i]*(1-t/299) + t_pos[i] * t/299  for i in list(t_pos.keys())}
    ax.clear() #clear axes
    nx.draw(Gt, pos=interpolation,with_labels=True,node_size = 500,ax=ax)
    ax.set_xlim([-1.5,1.5])
    ax.set_ylim([-1.5,1.5])
    

# run and save
ani = animation.FuncAnimation(fig, anim, repeat=False, frames=300, interval=100)
plt.show()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接