matplotlib ArtistAnimation返回空白视频 [英] matplotlib ArtistAnimation returns a blank video
问题描述
我正在尝试制作随时间变化的networkx图的动画.我正在使用networkx_draw实用程序创建图表的matplotlib图形,并使用matplotlib的ArtistAnimation模块从networkx生成的艺术家创建动画.我对这里的操作做了最小程度的复制:
I'm trying to produce an animation of a networkx graph changing over time. I'm using the networkx_draw utilities to create matplotlib figures of the graph, and matplotlib's ArtistAnimation module to create an animation from the artists networkx produces. I've made a minimum reproduction of what I'm doing here:
import numpy as np
import networkx as nx
import matplotlib.animation as animation
import matplotlib.pyplot as plt
# Instantiate the graph model
G = nx.Graph()
G.add_edge(1, 2)
# Keep track of highest node ID
G.maxNode = 2
fig = plt.figure()
nx.draw(G)
ims = []
for timeStep in xrange(10):
G.add_edge(G.maxNode,G.maxNode+1)
G.maxNode += 1
pos = nx.drawing.spring_layout(G)
nodes = nx.drawing.draw_networkx_nodes(G, pos)
lines = nx.drawing.draw_networkx_edges(G, pos)
ims.append((nodes,lines,))
plt.pause(.2)
plt.cla()
im_ani = animation.ArtistAnimation(fig, ims, interval=200, repeat_delay=3000,blit=True)
im_ani.save('im.mp4', metadata={'artist':'Guido'})
在实时显示人物时,该过程工作正常,它可以精确地产生我想要的动画.而且它甚至在脚本末尾的图形中生成循环动画,这也是我想要的,这表明动画处理有效.但是,当我打开保存在磁盘上的"im.mp4"文件时,它是一幅空白的白色图像,运行了预期的时间,从不显示任何实时显示的图形图像.
The process works fine while displaying the figures live, it produces exactly the animation I want. And it even produces a looping animation in a figure at the end of the script, again what I want, which would suggest that the animation process worked. However when I open the "im.mp4" file saved to disk, it is a blank white image which runs for the expected period of time, never showing any of the graph images which were showed live.
我使用的是networkx版本1.11和matplotlib版本2.0.我将ffmpeg用于动画,并在Mac OSX 10.12.3上运行.
I'm using networkx version 1.11, and matplotlib version 2.0. I'm using ffmpeg for the animation, and am running on a Mac, OSX 10.12.3.
我做错了什么?
推荐答案
简短的答案:如果您不想动画为空,请不要清除轴! IE.删除行plt.cla()
.然后,您还应该删除初始的nx.draw(G)
,因为它不会添加到ims
数组中,否则会在动画的每一帧中停留.
The short answer: If you don't want to have an empty animation, do not clear the axes! I.e. remove the line plt.cla()
. You should then also remove the initial nx.draw(G)
, because this is not added to the ims
array and would otherwise stick around in every frame of the animation.
在此问题中可以找到原因和更详细的解释,
Matplotlib视频创建,其中也处理了类似的情况.
The reasons and a longer explanation can be found in this question,
Matplotlib video creation, where a similar case is tackled.
缺点当然是,当删除plt.cla()
时,屏幕上会出现拥挤的动画.因此,您需要决定是在屏幕上绘制还是预先保存.
The drawback is of course that when removing the plt.cla()
you'll end up with a crowded animation on screen; so you need to decide whether to plot on screen or whether to save beforehands.
这篇关于matplotlib ArtistAnimation返回空白视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!