bad_chemist
bad_chemist

Reputation: 343

Why is the first iterator in frames in FuncAnimation repeated?

I am running a simple test on FuncAnimation when I noticed that the first index in frames is being repeated. This is the code that I have:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt 
import matplotlib.animation as animation

fig = plt.figure( figsize=(10,6) ) 
ax = fig.add_subplot(111, projection='3d')

Writer = animation.writers['ffmpeg']
writer = Writer(fps=20, metadata=dict(artist='Me'))

def animate(i):
    x = np.linspace(0, 2*np.pi, 120)
    y = np.cos(i*x)
    z = x 
    ax.clear()
    print(i)
    im = ax.plot(x, y, z)

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=range(5), repeat=False, blit=False)
ani.save("movie.mp4", writer=writer)
plt.show()

When I run this, I get the following output:

0
0
1
2
3
4

What I do not understand is why are the 0's showing up twice in the output?

Upvotes: 1

Views: 969

Answers (1)

Domarm
Domarm

Reputation: 2550

The reason is, that You are not passing init_func attribute into FuncAnimation. This quote from documentation explains why:

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.

So when You start Your animation, first frame is always drawn as a result of init_func. You can set custom init_func, which is called in the beginning of animation instead.

Upvotes: 3

Related Questions