使用 networkx 和 matplotlib 的网络平滑动画

Smooth animation of a network using networkx and matplotlib

我正在尝试为 networks 图形的布局更改制作动画。我的测试代码如下:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import networkx as nx
import random
import numpy as np

fig = plt.figure()

node_number = 0
G =nx.Graph()
G.add_node(node_number, Position=np.asarray([random.randrange(0,100), random.randrange(0,100)]))

while True:
    if node_number < 50:
        node_number += 1
        G.add_node(node_number, Position=np.asarray([random.randrange(0,100), random.randrange(0,100)]))
        ns=list(G.nodes())
        ns.remove(node_number)
        G.add_edge(node_number, random.choice(ns))
    else:
        break

source_pos = list(nx.get_node_attributes(G, 'Position').values())
target_pos = list(nx.circular_layout(G).values())
def anim(t):
    global source_pos
    global target_pos
    interpolation = np.asarray(source_pos)*(1-t) + np.asarray(target_pos)*t
    plt.clf()
    plt.cla()
    nx.draw(G, pos=interpolation)
    ax= plt.gca()
    ax.collections[0].set_edgecolor("#000000")

ani = animation.FuncAnimation(fig, anim, repeat=False, frames=300, interval=20)
plt.show()

无论我如何调整动画的间隔或帧,代码都会生成奇怪的过渡。我附上了上述代码的输出。谁能帮我解决我犯的错误?

当您在 anim 函数中传递 t 时,您传递了一个帧数,因此您必须在这一行中将其除以帧数:

interpolation = np.asarray(source_pos)*(1-t/299) + np.asarray(target_pos)*t/299

(因为 frames 计数为 300:0 到 299)

此外,您可以使用 while node_number < 50: 并删除测试部分而不是 while True

编辑 所以我使用 random.random() 来获得 -1 和 1 之间的随机位置。 动画好多了。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import networkx as nx
import random
import numpy as np

fig = plt.figure()

G =nx.Graph()
node_number = 0
while node_number < 50:
        G.add_node(node_number,
                   Position=np.asarray([random.random() * 2 -1,
                                        random.random() * 2 -1]))
        ns=list(G.nodes())
        G.add_edge(node_number, random.choice(ns))
        node_number += 1


s_pos = nx.get_node_attributes(G, 'Position')
t_pos = nx.circular_layout(G)


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 range(50)}
    plt.clf()
    plt.cla()
    nx.draw(G, pos=interpolation)


ani = animation.FuncAnimation(fig, anim, repeat=False, frames=300, interval=20)
plt.show()