我编写了以下代码来设置jupyter笔记本中图形节点的颜色的动画。
%matplotlib notebook
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation
def update(i,G,pos,t,ax):
ax.clear()
cmap = matplotlib.cm.get_cmap('Blues')
color_map = []
for node in G:
color_map.append(cmap(t[i]))
nx.draw(G,pos,node_color=color_map,ax=ax)
t = np.linspace(0,1,10)
G = nx.petersen_graph()
pos = nx.spring_layout(G) # positions for all nodes
fig, ax = plt.subplots(figsize=(8,6))
ani = matplotlib.animation.FuncAnimation(fig,update,repeat=True,interval=100,frames=len(t),repeat_delay=10,fargs=(G, pos, t, ax))
plt.show()
尽管这对我来说是可行的,但我希望能够在像这样的函数中执行整个程序
%matplotlib notebook
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation
def update(i,G,pos,t,ax):
ax.clear()
cmap = matplotlib.cm.get_cmap('Blues')
color_map = []
for node in G:
color_map.append(cmap(t[i]))
nx.draw(G,pos,node_color=color_map,ax=ax)
def anim():
t = np.linspace(0,1,10)
G = nx.petersen_graph()
pos = nx.spring_layout(G) # positions for all nodes
fig, ax = plt.subplots(figsize=(8,6))
ani = matplotlib.animation.FuncAnimation(fig,update,repeat=True,interval=100,frames=len(t),repeat_delay=10,fargs=(G, pos, t, ax))
plt.show()
anim()
但是,此脚本不起作用,因为与第一个脚本不同的是,tha动画不会显示在jupyter笔记本中。有人可以告诉我为什么吗?请注意,我想在jupyter Notebook的控制台中显示动画,而不是将其保存为gif。