Skip to main content
 首页 » 编程设计

python之使用 NetworkX 动画图形扩散

2025年05月04日10dyllove98

我想在图形上(最好是在 NetworkX 中)为一个过程制作动画。我已经看过this question .但是,当我运行解决方案中给出的代码时,我只看到了最终输出。此外,这不会以某种可用格式保存动画。

假设我们有如下图表:

import networkx as nx 
 
g = nx.Graph() 
g.add_edges_from([(1, 2), (2, 3), (1, 3), (1, 4), (3, 4), (4, 5), (5, 9), (4, 9)]) 

此外,我们有一组初始节点,我们称之为事件节点:

active = {1, 3} 

直觉上,我想要做的是动画化每个事件节点将如何导致图中的其他节点及时变为事件状态。因此,如果我们假设一个模型,其中如果至少有两个邻居变得活跃,则每个节点都会变得活跃,那么在第二次迭代中,活跃节点的集合将是:

active = {1, 3, 2, 4} 

在下一次迭代中,事件节点的集合将是:

active = {1, 3, 2, 4, 5}. 

在最后一次迭代中,图中的所有节点都将变为事件状态:

active = {1, 3, 2, 4, 5, 9} 

这个过程称为引爆过程,是网络中信息传播的一个例子。您可以在下面看到该算法的一个非常简单的实现。

def tipping(graph, seed_set, thr=2): 
    active = seed_set 
    has_changed = False 
    for n in filter(lambda n: n not in active, graph.nodes()): 
        if len(filter(lambda nei: nei in active, graph.neighbors(n))) >= thr: 
            active.add(n) 
            has_changed = True 
    if has_changed: 
        return tipping(graph, active, thr) | active 
    return active 

我想知道是否有任何方法可以可视化此过程。我知道我可以使用 networkX 中的 nx.draw() 函数绘制网络。但是,我还没有看到任何函数可以为这种情况生成动画或任何其他有用的输出。

一个可能的解决方案可能是在流程的每个步骤中用不同的节点颜色绘制图形,保存它们中的每一个并用所有保存的图片制作一个 gif 动画。

如何使用 Networkx 为扩散设置动画?动画最好在 IPython 笔记本中运行。

请您参考如下方法:

这是一个简化的、精简的动画示例,对于任何寻找 networkx 动画的人来说应该会有用。如果您运行它,它实际上会起作用。

import numpy as np 
import networkx as nx 
import matplotlib.pyplot as plt 
from matplotlib import animation 
 
 
def simple_update(num, n, layout, G, ax): 
    ax.clear() 
 
    # Draw the graph with random node colors 
    random_colors = np.random.randint(2, size=n) 
    nx.draw(G, pos=layout, node_color=random_colors, ax=ax) 
 
    # Set the title 
    ax.set_title("Frame {}".format(num)) 
 
 
def simple_animation(): 
 
    # Build plot 
    fig, ax = plt.subplots(figsize=(6,4)) 
 
    # Create a graph and layout 
    n = 30 # Number of nodes 
    m = 70 # Number of edges 
    G = nx.gnm_random_graph(n, m) 
    layout = nx.spring_layout(G) 
 
    ani = animation.FuncAnimation(fig, simple_update, frames=10, fargs=(n, layout, G, ax)) 
    ani.save('animation_1.gif', writer='imagemagick') 
 
    plt.show() 
 
simple_animation() 

您需要一个函数 simple_animation 来设置和运行动画,还需要一个函数 simple_update 来更新动画。 fargs 允许您将参数传递给 simple_update 函数。

这个动画只是设置了随机颜色,你应该能够将它改编成任何其他目的。