【发布时间】:2018-09-02 05:36:13
【问题描述】:
matplotlib.animation.FuncAnimation 的文档说:
init_func : [...] 此函数将在第一帧之前调用一次。
但每当我使用FuncAnimation 时,init_func 就会被多次调用。
您可以通过在basic example from Matplotlib's website 中添加打印语句来看到这一点:
"""
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)
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():
# ---> Adding a print statement here <---
print('Initializing')
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()
除了产生可爱的情节,它立即给出标准输出:
Initializing
Initializing
如果我让动画继续运行,init_func 实际上会被一遍又一遍地调用!
这是错误还是功能?我该怎么办?
一点背景:我使用init_func初始化多个绘图as described here,只在一个类内:
class MyAnimation:
def __init__(self, n):
self.fig, self.ax = plt.subplots()
self.n = n
self.lines = []
def run_animation(self):
def init():
for i in range(self.n):
line = ax.plot([], [])[0]
self.lines.append(line)
return self.lines
def animate(i):
... # Update lines
return self.lines
animation = FuncAnimation(self.fig, animate, init_func=init, blit=True)
plt.show()
当然,如果init() 被多次调用,这是没有意义的,因为额外的行将附加到self.lines。
我的方法不是很好的做法吗?
我应该在init() 函数中设置self.lines = [] 吗?
【问题讨论】:
标签: python animation matplotlib