[英]Matplotlib FuncAnimation not animating line plot
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.
请记住,这是一个随机图,因此实际数字将随每次运行而变化。
Okay, I think what you want is to only plot up to the i -th index for frame i of the animation. 好的,我认为您只想为动画的第i帧绘制第i个索引。 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. 注意,我将帧数更改为
len(x)+1
并增加了间隔,因此它的速度足够慢才能看到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.