And*_*pez 10 python animation matplotlib
我正在尝试实现一个输出动画情节的功能.
如果我将simple_anim.py(来自matplotlib示例)作为基础:
"""
A simple example of an animated plot
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01) # x-array
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x+i/10.0)) # update the data
return line,
#Init only required for blitting to give a clean slate.
def init():
line.set_ydata(np.ma.array(x, mask=True))
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
interval=25, blit=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)
实际上它有效.
但是,如果我在函数内部关闭此代码(为了提供更改参数,并避免为每个可能的参数值执行显式文件):
"""
A simple example of an animated plot
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def a():
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01) # x-array
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x+i/10.0)) # update the data
return line,
#Init only required for blitting to give a clean slate.
def init():
line.set_ydata(np.ma.array(x, mask=True))
return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
interval=25, blit=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)
然后调用该函数,图形图保持白色.事实上,它永远不会进入动画功能.
我知道我错过了一些信息,这就是为什么它不起作用.有人能给我一些提示吗?
非常感谢你,
安德烈斯
tac*_*ell 16
发生这种情况的原因是更新窗口的计时器和回调是对象的属性ani.如果你没有对它进行引用,那么ani在垃圾收集中你的定时器/回调就会消失.
解决方案是让您的函数返回ani并在代码中保留对它的引用:
def a(...):
# stuff
ani = animation.FuncAnimation(...)
# more stuff
return ani
outer_ani = a(...)
Run Code Online (Sandbox Code Playgroud)
这个问题(参见github#1656)已经讨论过,但尚未解决.
| 归档时间: |
|
| 查看次数: |
4476 次 |
| 最近记录: |