我有两个随机向量,用于创建线图。使用相同的向量,我想为线条设置动画,但动画是静态的 - 它只是绘制原始图形。关于如何制作这样的线图动画有什么建议吗?
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)
动画的最终帧应如下图所示。请记住,这是一个随机图,因此实际数字会随着每次运行而变化。
最佳答案
好吧,我认为您想要的只是绘制动画的第 i 帧的第 i 索引。在这种情况下,您可以仅使用帧号来限制显示的数据:
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)
请注意,我将帧数更改为 len(x)+1
并增加了间隔,这样看起来就足够慢了。
关于python-3.x - Matplotlib FuncAnimation 没有动画线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26875827/