python 动画网络图

3z6pesqy  于 2023-03-16  发布在  Python
关注(0)|答案(1)|浏览(119)

我想画一个动态的网络来展示它是如何随着时间的推移而变化的,我已经找到了如何在给定两个单一状态(这里称为 s_post_pos)的情况下动画化一个网络,但是我想做的更进一步,因为我想一行一行地填充我的网络,我想我需要通过在函数anim(t)中迭代我的 Dataframe 来更新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)
8i9zcol2

8i9zcol21#

如果我没理解错的话,您希望您的网络逐步(逐行)出现在动画中,一种方法是根据 Dataframe 中最多t的行,在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()

相关问题