2016-11-11 85 views
1

我想学习如何使用matplotlib的内置funcAnimation类来动画阴谋。对于这个例子,我只想生成一个随机分布的正常值的二维散点图,并在每次更新点时为该图添加一个点(使出现的点出现动画)。示例代码如下:Matplotlib funcAnimation不打开/显示阴谋

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
import random 

plt.ion() 
fig, ax = plt.subplots() 
scat = ax.scatter([],[]) 
scat.axes.axis([-5, 5, -5, 5]) 

def update(point): 
    array = scat.get_offsets() 
    array = np.append(array, point) 
    scat.set_offsets(array) 
    return scat 

def data_gen(): 
    for _ in range(0,100): 
     point = np.random.normal(0, 1, 2) 
     yield point 

ani = animation.FuncAnimation(fig, update, data_gen, interval=25, blit=False) 
plt.show() 

当我运行此代码时,没有任何反应。终端搅动了几秒钟,然后什么也没有发生。

我使用这个作为我的指南:http://matplotlib.org/examples/animation/animate_decay.html,如果我使用线图而不是散点图(本质上只是替换该示例的生成器中生成的点的方式),它“起作用”尽可能远它会生成数据并更新绘图。但这不是我想要的显示,我希望看到该点出现在散点图上。要使用散点图,我不需要使用set_data,因为这不是散点图的有效方法;所以我使用了在这个例子中看到的np.append()方法: Dynamically updating plot in matplotlib

所以我的问题是,我在做这个错误导致动画不显示出来的代码?

编辑:我只是试着/发现,如果我补充一下: mywriter = animation.FFMpegWriter(FPS = 60) ani.save( 'myanimation.mp4',作家= mywriter) 它产生包含动画的mp4,我无法让它在代码运行时动态显示。所以如果你能够诊断它,请关注这个问题。谢谢。

+0

如果我只是删除了'plt.ion()'行,你的代码对我来说工作得很好。你需要这些吗?通常'ion()'仅在ipython中绘图时使用,我不确定这是否是你想要的。 – ImportanceOfBeingErnest

+0

谢谢!我只是在看示例代码,他们都有这样的;所以我认为这是动画所必需的。这解决了它! – Zach

回答

1

为了将来的参考,@ImportanceOfBeingErnest指出plot.ion()不是必需的,并且特定于在ipython中绘图。删除它可以解决问题。