How do I solve the index error generated in matplotlib animation?

Viewed 224

I am learning the animation tool in matplotlib, but I am running into error in the following code.

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

x = np.array([1,2,4,6,4])
y = np.array([2,5,4,7,9])

x_points, y_points = [],[]

fig, ax = plt.subplots()
xdata, ydata = [],[]
line, = plt.plot([],[],'ro')

def init():
    line.set_data([],[])
    return line, 

def animate(i):
   x_points.append(x[i])
   y_points.append(y[i])
   line.set_data(x_points,y_points)
      return line 

ani = animation.FuncAnimation(fig,animate,init_func=init,
   frames = 200,interval=500,blit=False)

plt.show()

I am getting the below error. How do I solve it?

IndexError: index 5 is out of bounds for axis 0 with size 5
1 Answers

You have too many frames (200) for the lists x and y. Since x and y both have the length of 5, the maximum value you can set the frames argument to is 5:

ani = animation.FuncAnimation(fig, animate, init_func=init, frames=5, interval=500, blit=False)

To elaborate, each frame uses up one index of the x and y lists.

Related