简体   繁体   中英

How do I slow down my matplotlib animation?

I'm trying to plot a line and I've three points for it which are in two lists: x,y. The code works but I can't see the line being rendered in front of me and hence, it keeps looking like an image. How do I slow down this animation? Here's the code:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure()
ax = plt.axes(xlim=(0, 105), ylim=(0, 68))
line, = ax.plot([], [], lw=2)

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

def animate(i):
    x = np.array([23.94, 34.65, 28.14])
    y = np.array([5.984, 6.664, 6.256])  
    #x = np.linspace(0, 2, 1000)
    #y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,


anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=1, interval=1, save_count = 50, blit=True)


FFWriter = animation.FFMpegWriter()
#ani.save('particle_box.avi', writer = FFWriter)
#anim.save('basic.mp4',  writer = FFWriter)#, fps=30)#, extra_args=['-vcodec', 'libx264'])

plt.show()

Well, first, your animation has only two effective states because the animation function isn't actually doing anything.

You can factor out the definition of x and y since they don't actually change. To actually perform the animation, what you should do is make the points on the line change with every call of anim_func , which can be done by slicing x and y :

x = np.array([23.94, 34.65, 28.14])
y = np.array([5.984, 6.664, 6.256])  

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

Lastly, you should modify your FuncAnimation creation to have a longer interval, for example:

anim = animation.FuncAnimation(fig, animate, init_func=init,
                              interval=1000, save_count = 50, blit=True)
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure()
ax = plt.axes(xlim=(0, 105), ylim=(0, 68))
line, = ax.plot([], [], lw=2)
import math
def init():
    line.set_data([], [])
    return line,

x = np.array([])
y = np.array([])

for i in range(1000):
    x = np.append(x, i)
    y = np.append(y, 10 + 10 * math.sin(i / 10))

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

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(x), interval=1, save_count = 50, blit=True)


FFWriter = animation.FFMpegWriter()
#ani.save('particle_box.avi', writer = FFWriter)
#anim.save('basic.mp4',  writer = FFWriter)#, fps=30)#, extra_args=['-vcodec', 'libx264'])

plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM