【发布时间】:2017-10-11 16:54:24
【问题描述】:
我想根据我已经生成并存储的指标为我的图表着色。这些将是我的帧 [每个帧的长度 = 图的节点数],用于 matplotlib 动画,应该传递给图的 node_color 属性。怎么把它变成动画?这是一个小图的最小非工作示例:
# 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: the animation function must return a sequence of Artist objects。
我有一种强烈的感觉,我在这里错过了一些明显的简单方法,而且这个问题是微不足道的。但是由于我不经常使用动画功能,所以我不太了解它。
【问题讨论】:
标签: python animation matplotlib networkx