Matplotlib FuncAnimation 不是动画线图 [英] Matplotlib FuncAnimation not animating line plot

查看:38
本文介绍了Matplotlib FuncAnimation 不是动画线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

好吧,我想你想要的只是绘制到 i 帧的第 i 个索引em> 的动画.在这种情况下,您可以仅使用帧数来限制显示的数据:

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)

注意,我将帧数更改为 len(x)+1 并增加了间隔,使其速度很慢,无法看到.

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

这篇关于Matplotlib FuncAnimation 不是动画线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆