Networkx + Matplotlib 动画出现问题 - 'NoneType' 对象没有属性 'set_visible'

Trouble with Networkx + Matplotlib Animations - 'NoneType' object has no attribute 'set_visible'

我在将以下 DFS 动画设置为 运行 时遇到了一些问题。 我相信这可能是因为没有背景 canvas,但我不确定如何解决这个问题,因为所有其他类似的在线实现都使用 plt.plot 而不是 nx.draw 来保存图像待展示。

有人可以提供指导吗?

import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation

fig = plt.figure()
ax = plt.gca()
colors = [0]*len(g)
cmap = plt.get_cmap("autumn")

g = nx.random_tree(20)
pos = nx.fruchterman_reingold_layout(g, k=0.1)


ims = [[nx.draw_networkx(g, pos, node_color = colors, cmap = cmap, ax = ax, vmin=0.0, vmax=1.0)]]

artists = [(nx.draw_networkx(g, pos, node_color = colors, cmap = cmap, ax = ax, vmin=0.0, vmax=1.0),)]

stack = [0] 

while stack:
    node = stack.pop()
    
    if colors[node]: 
        continue
        
    colors[node] = 0.8
    stack += list(g[node].keys())
    
    img = nx.draw_networkx(g, pos, node_color=colors, cmap=cmap, ax=ax, vmin=0.0, vmax=1.0)
    ims += [img]
    
anim = ArtistAnimation(fig, ims, blit = True)
# plt.show()

您的代码的问题是 nx.draw_networkx() 没有 return 任何东西,使用 FuncAnimation 方法总是更容易。首先,你需要创建一个颜色生成器,让动画函数在每次调用时切换到下一个设置的颜色。然后使用 FuncAnimation 你可以动画你的帧(图):

import networkx as nx
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.animation as animation

matplotlib.use('TkAgg')
plt.ion()

g = nx.random_tree(20)
colors = [0] * len(g)
cmap = plt.get_cmap('autumn')
pos = nx.fruchterman_reingold_layout(g, k=0.1)

# here you make the generator
def change_colors():
    stack = [0]
    
    yield colors

    while stack:
        node = stack.pop()
        if colors[node]:
            continue

        colors[node] = 0.8
        stack += list(g[node].keys())

        yield colors

# instantiate your generator
color_gen = change_colors()


def update_frame(n):
    # clear the plot
    plt.cla()
    # here switch to the next colors
    colors = next(color_gen)
    # then draw
    nx.draw(g, pos, with_labels=True, node_color=colors, cmap=cmap, vmin=0.0, vmax=1.0)


ani = animation.FuncAnimation(plt.gcf(), update_frame, repeat=False, interval=1000)

plt.ioff()
plt.show()

这会给你: 您可以通过将 plt.show() 替换为 ani.save('anim.gif', writer='imagemagick').

将其保存为 gif 文件