【问题标题】:How do I solve the index error generated in matplotlib animation?matplotlib动画中产生的索引错误如何解决?
【发布时间】:2020-12-29 13:04:05
【问题描述】:

我正在学习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

【问题讨论】:

    标签: python python-3.x matplotlib matplotlib-animation


    【解决方案1】:

    对于列表xy,您的帧数过多(200)。由于xy 的长度均为5,因此您可以将frames 参数设置为的最大值为5

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

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

    【讨论】:

    • 感谢您的回答。但我有一个新错误。我的代码没有绘制数据。
    • @MonojitSarkar 也许这可能是一个单独的问题?
    • @MonojitSarkar 请不要在同一个帖子上更改您的问题,因为这样用户的答案将失效。相反,请单独发布一个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 2017-04-29
    • 2015-12-04
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多