2

我正在学习 matplotlib 中的动画工具,但在以下代码中遇到错误。

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

我收到以下错误。我该如何解决?

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

1 回答 1

1

对于列表和 ,您的帧( 200)过多。由于和都具有 的长度,因此您可以将参数设置为的最大值是:xyxy5frames5

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

详细地说,每一帧都使用了xy列表的一个索引。

于 2020-12-29T13:12:37.280 回答