【问题标题】:matplotlib funcanimation update function is called twice for first argumentmatplotlib funcanimation 更新函数为第一个参数调用两次
【发布时间】:2017-03-24 00:36:45
【问题描述】:

浏览了一些关于matplotlib动画的教程,遇到了这个问题。我正在使用 matplotlib.animation funcanimation 如下:

import matplotlib.animation as animation
import numpy as np
from pylab import *

def ani_frame():
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

im = ax.imshow(rand(7, 7), cmap='gray', interpolation='nearest')

tight_layout()

    def update_img(n):
        print(n)
        tmp = rand(7, 7)
        im.set_data(tmp)
        return im

    ani = animation.FuncAnimation(fig, update_img, np.arange(0, 20, 1), interval=200)
    writer = animation.writers['ffmpeg'](fps=5)

    ani.save('demo.mp4', writer=writer)
    return ani

ani_frame()

这会生成以下输出:

0 0 1 2 3 4 5

等等。它两次调用第一个参数。我怎样才能防止这种情况发生?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以使用初始化函数并使用init_func 参数将其提供给FuncAnimation。这样第一次调用将在 init 函数上,而不是在 update 函数上。

    import matplotlib.animation as animation
    import numpy as np
    from pylab import *
    
    def ani_frame():
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
    
        im = ax.imshow(rand(7, 7), cmap='gray', interpolation='nearest')
    
        tight_layout()
    
        def init():
            #do nothing
            pass
    
        def update_img(n):
            print(n)
            tmp = rand(7, 7)
            im.set_data(tmp)
    
        ani = animation.FuncAnimation(fig, update_img, np.arange(0, 20, 1),
                                      init_func=init, interval=200)
        writer = animation.writers['ffmpeg'](fps=5)
    
        ani.save('demo.mp4', writer=writer)
        return ani
    
    ani_frame()
    

    这会打印 0 1 2 3 ....

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-02
      • 2021-12-01
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      相关资源
      最近更新 更多