python-3.x - Matplotlib FuncAnimation 没有动画线图

标签 python-3.x numpy matplotlib

我有两个随机向量,用于创建线图。使用相同的向量,我想为线条设置动画,但动画是静态的 - 它只是绘制原始图形。关于如何制作这样的线图动画有什么建议吗?

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)

动画的最终帧应如下图所示。请记住,这是一个随机图,因此实际数字会随着每次运行而变化。

enter image description here

最佳答案

好吧,我认为您想要的只是绘制动画的第 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/

相关文章:

python - 将第二个 y 轴引入具有多个绘图的 relplot() 调用中

python - Cartopy map 填充整个轴

python - 我如何找出我的代码的哪些部分在 Python 中效率低下

python - 创建一个幻方

python - 在 Python 中优雅地将排序推广到字典中?

python - 极地立体图

python-3.x - 音频 .wav 文件的二进制分类

python-3.x - 如何解决错误:[Errno 2]没有这样的文件或目录:'C:\\Program Files\\Python37\\lib\\venv\\scripts\\nt\\python_d.exe'

python - Cython:在没有 NumPy 数组的情况下创建内存 View ?

python - 在新维度中堆叠数组