FuncAnimation produces one more frame than intended at startup

Viewed 46

enter image description here

Watch closely as the GUI starts up. The first iteration appears to be doubling for some reason. I have the frames parameter set to 4 (equivalent to range(4)), so we should only see four points, but we have 5. Here is the code:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random


def animate(_):
    x = random.uniform(0, 10)
    y = random.uniform(0, 10)

    plt.scatter(x, y, color='maroon', marker='x')


plt.xlim((0, 10))
plt.ylim((0, 10))
ani = FuncAnimation(plt.gcf(), animate, frames=4, interval=1000, repeat=False)
plt.show()

How can this be fixed?

1 Answers

Looking up FuncAnimation's manual page:

init_func: callable, optional

A function used to draw a clear frame. If not given, the results of drawing from the first item in the frames sequence will be used. This function will be called once before the first frame.

As no explicit init_func is given, animate(0) is called instead. You can provide a dummy init_func to prevent this.

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random

def init_func():
    pass

def animate(frame):
    x = random.uniform(0, 10)
    y = random.uniform(0, 10)
    plt.scatter(x, y, color='maroon', marker='x')

plt.xlim((0, 10))
plt.ylim((0, 10))
ani = FuncAnimation(plt.gcf(), animate, init_func=init_func, frames=4, interval=1000, repeat=False)
plt.show()
Related