作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试实现一个输出动画图的函数。
如果我将 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()
有效地工作。
但是,如果我在一个函数中关闭这段代码(为了提供不断变化的参数,并避免为每个可能的参数值做一个显式文件):
"""
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()
然后调用该函数,图形图保持白色。事实上,它永远不会进入动画功能。
我知道我遗漏了一些信息,这就是它不起作用的原因。有人可以给我一些提示吗?
非常感谢,
安德烈斯
最佳答案
发生这种情况的原因是更新窗口的定时器和回调是对象 ani
的属性。如果你不保留对它的引用,那么垃圾中的 ani
和你的计时器/回调就会消失。
解决方案是让您的函数返回 ani
并在您的代码中保留对它的引用:
def a(...):
# stuff
ani = animation.FuncAnimation(...)
# more stuff
return ani
outer_ani = a(...)
这个问题(参见 github #1656)已经过讨论,但没有解决。
关于 python matplotlib : unable to call FuncAnimation from inside a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21099121/
我是一名优秀的程序员,十分优秀!