第一个参数调用matplotlib funcanimation更新函数两次

Bis*_*ara 5 python matplotlib

在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()
Run Code Online (Sandbox Code Playgroud)

这会生成以下输出:

0 0 1 2 3 4 5

等等.它两次调用第一个参数.我怎么能阻止这个?

Imp*_*est 8

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

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()
Run Code Online (Sandbox Code Playgroud)

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