我目前正在使用matplotlib的FuncAnimation函数,遇到问题。我的代码遵循与以下代码类似的逻辑
import matplotlib.animation as animation
import matplotlib.pyplot as plt
class Example:
def __init__(self):
self.fig = plt.figure()
def update(self, num):
print("This is getting called")
def animate(self):
ani = animation.FuncAnimation(self.fig, update, interval=100)
def main():
obj = Example()
obj.animate()
if __name__ == "__main__":
main()
目前,我的代码还没有打印出来“这正在被调用”。我尝试将self.update而不是update传递给FuncAnimation,但无济于事。在调用FuncAnimation之前,我还尝试编写全局更新,这也不起作用。我想知道是否有人可以帮助我。
最佳答案
@ReblochonMasque的回答是正确的,说您需要使用plt.show()
实际显示该图。
但是,您不需要从动画函数返回任何内容(除非您想使用blitting,在这种情况下,您需要将Artists
的可迭代值返回到blit)。
而且,如果您将FuncAnimation
设为类变量(self.ani
),则可以确保随时随地调用show()
,而不仅是在“ animate”函数中。
import matplotlib.animation as animation
import matplotlib.pyplot as plt
class Example:
def __init__(self):
self.fig, self.ax = plt.subplots()
def update(self, i):
print("This is getting called {}".format(i))
self.ax.plot([i,i+1],[i,i+2])
def animate(self):
self.ani = animation.FuncAnimation(self.fig, self.update, interval=100)
def main():
obj = Example()
obj.animate()
plt.show()
if __name__ == "__main__":
main()