Matplotlib FuncAnimation not animating line plot

六月ゝ 毕业季﹏ 提交于 2021-01-27 18:29:42

问题


I have two random vectors which are used to create a line plot. Using the same vectors, I would like to animate the line but the animation is static - it just plot the original graph. Any suggestions on how to animate such a line plot?

import numpy as np
import matplotlib.pyplot as py
from matplotlib import animation

# random line plot example

x = np.random.rand(10)
y = np.random.rand(10)

py.figure(3)
py.plot(x, y, lw=2)
py.show()

# animation line plot example

fig = py.figure(4)
ax = py.axes(xlim=(0, 1), ylim=(0, 1))
line, = ax.plot([], [], lw=2)

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

def animate(i):
    line.set_data(x, y)
    return line,

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

The final frame of the animation should look something like the plot below. Keep in mind that this is a random plot so the actual figure will change with each run.

enter image description here


回答1:


Okay, I think what you want is to only plot up to the i-th index for frame i of the animation. In that case, you can just use the frame number to limit the data displayed:

import numpy as np
import matplotlib.pyplot as py
from matplotlib import animation

x = np.random.rand(10)
y = np.random.rand(10)

# animation line plot example

fig = py.figure(4)
ax = py.axes(xlim=(0, 1), ylim=(0, 1))
line, = ax.plot([], [], lw=2)

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

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

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(x)+1,
                               interval=200, blit=False)

Notice I changed the number of frames to len(x)+1 and increased the interval so it's slow enough to see.



来源:https://stackoverflow.com/questions/26875827/matplotlib-funcanimation-not-animating-line-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!