我想根据我已生成并存储的指标为我的图表着色。对于应该传递给图的node_color属性的matplotlib动画,这些将是我的帧[长度的每一帧=图形的节点数]。如何将其变成动画?以下是小图表的最小非工作示例:
# number of nodes
size = 10.
# generate graph
G=nx.complete_graph(size)
# generating input frames here, since my data is too big
# its important that the frames go as input and is not generated
# on the fly
frame = np.random.random_integers(0, 5, (size, size)) # random ndarray between 0 and 5, length and number of frames = number of nodes in the graph
# draw the topology of the graph, what changes during animation
# is just the color
pos = nx.spring_layout(G)
nodes = nx.draw_networkx_nodes(G,pos)
edges = nx.draw_networkx_edges(G,pos)
plt.axis('off')
# pass frames to funcanimation via update function
# this is where I get stuck, since I cannot break
# out of the loop, neither can I read every array of
# the ndarray without looping over it explicitly
def update(i):
for i in range(len(frame)):
# instead of giving frame as input, if I randomly generate it, then it works
nc = frame[i] # np.random.randint(2, size=200)
nodes.set_array(nc)
return nodes,
# output animation; its important I save it
ani = FuncAnimation(fig8, update, interval=50, blit=True)
ani.save('crap.gif', writer='imagemagick', savefig_kwargs={'facecolor':'white'}, fps=1)
由于所述问题,动画最终只显示最后一帧或仅显示第一帧。
请注意,如果我在更新函数中使用nx.draw(),我会收到以下错误:RuntimeError:动画函数必须返回一系列Artist对象。
我有一种强烈的感觉,我错过了一些明显的简单方法,这个问题很简单。但由于我不经常使用动画功能,我无法理解它。
答案 0 :(得分:1)
你快到了:update
只想要时间t的状态。如果我正确阅读了您的代码,那么您将遍历t
内的所有update
。因此,只需摆脱该循环并将frames
参数添加到FuncAnimation
,以便知道要检查的时间。
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from matplotlib.animation import FuncAnimation
# number of nodes
size = 10
# generate graph
G=nx.complete_graph(size)
# generating input frames here, since my data is too big
# its important that the frames go as input and is not generated
# on the fly
frame = np.random.random_integers(0, 5, (size, size)) # random ndarray between 0 and 5, length and number of frames = number of nodes in the graph
# draw the topology of the graph, what changes during animation
# is just the color
pos = nx.spring_layout(G)
nodes = nx.draw_networkx_nodes(G,pos)
edges = nx.draw_networkx_edges(G,pos)
plt.axis('off')
# pass frames to funcanimation via update function
# this is where I get stuck, since I cannot break
# out of the loop, neither can I read every array of
# the ndarray without looping over it explicitly
def update(i):
# for i in range(len(frame)):
# instead of giving frame as input, if I randomly generate it, then it works
nc = frame[i] # np.random.randint(2, size=200)
nodes.set_array(nc)
return nodes,
# output animation; its important I save it
fig = plt.gcf()
ani = FuncAnimation(fig, update, interval=50, frames=range(size), blit=True)
ani.save('crap.gif', writer='imagemagick', savefig_kwargs={'facecolor':'white'}, fps=1)