Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib funcanimation update function is called twice for first argument

Going through some tutorials on matplotlib animations and encountered this problem. I am using the matplotlib.animation funcanimation as follows:

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()

This generates the following output:

0 0 1 2 3 4 5

and so on. It is calling the first argument twice. How can I prevent this?

like image 643
Bishara Avatar asked Mar 24 '17 00:03

Bishara


People also ask

What is blit in matplotlib animation?

The blit keyword is an important one: this tells the animation to only re-draw the pieces of the plot which have changed. The time saved with blit=True means that the animations display much more quickly. We end with an optional save command, and then a show command to show the result.

How do I stop func animation?

stop() . Alternatively you may stop the animation with anim. event_source. stop() .

What is PillowWriter?

The PillowWriter class from matplotlib. animation is a writer that allows us to save animations we create in matplotlib . Pillow is a fork of the Python Image Library (PIL). Both PIL and Pillow come with matplotlib .


Video Answer


1 Answers

You can use an initialization function and provide it to FuncAnimation using the init_func argument. That way the first call will be on the init function and not the update function.

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()

This prints 0 1 2 3 ....

like image 93
ImportanceOfBeingErnest Avatar answered Oct 26 '22 16:10

ImportanceOfBeingErnest