2

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.

enter image description here

wigging
  • 8,492
  • 12
  • 75
  • 117
  • I'm not sure what you mean by "using the same vectors" - in your example, x and y never change at all, hence the animation doesn't change. – Ajean Nov 11 '14 at 23:20
  • @Ajean What I'm trying to do is instead of creating the entire plot at once, I would like to animate from point 1 to point 2, etc. by using the animation feature of Matplotlib. – wigging Nov 11 '14 at 23:32

1 Answers1

2

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)

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

Ajean
  • 5,528
  • 14
  • 46
  • 69
  • To capture the last point of the plot, I had to use `len(x)+1` for the number of frames. – wigging Nov 12 '14 at 01:38
  • I'm also trying to do this for a scatter plot, so any suggestions would also be helpful: http://stackoverflow.com/questions/26892392/matplotlib-funcanimation-for-scatter-plot – wigging Nov 12 '14 at 17:01