Python Forum

Full Version: Animating Random Walk
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello. I am trying to animate this very simple 2D random walk program. However, I am not sure what the FuncAnimation function is suppose to do and why it isn't working.

Here is the program:


##################
# 2D Random Walk #
##################

import random
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation

xposition = [0]
yposition = [0]

def random_walk():
polar_angle = random.random()*2*math.pi
radius = random.random()

xposition.append( xposition[-1] + radius*math.cos(polar_angle) )
yposition.append( yposition[-1] + radius*math.sin(polar_angle) )

plt.plot( xposition, yposition, c = 'k' )

animation.FuncAnimation( fig = plt.figure(), func = random_walk(), interval = 1000 )
plt.show()


I found a lot of really complicated and hard to read algorithms when I was searching how to make a simple random walk program. Similarly, when I search how to use the FuncAnimation function, I am bombarded with hard to read code that I cannot understand.

I think that fig is the figure onto which the data will be plotted; func is the function to be called every interval, and interval is the time interval in microseconds between each call. I'm not sure why it doesn't work. I'm also not sure why the code I posted isn't displaying correctly. Perhaps, it's my browser.
Sorry. I fixed the display.

##################
# 2D Random Walk #
##################

import random
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation

xposition = [0]
yposition = [0]

def random_walk():
    polar_angle = random.random()*2*math.pi
    radius      = random.random()

    xposition.append( xposition[-1] + radius*math.cos(polar_angle) )
    yposition.append( yposition[-1] + radius*math.sin(polar_angle) )

    plt.plot( xposition, yposition, c = 'k' )

animation.FuncAnimation( fig = plt.figure(), func = random_walk(),
                         interval = 1000 )
plt.show()
Okay. For some reason this worked. I suppose adding i as a functional argument makes sense. However, I don't understand why I have to make the animation.FuncAnimation() a variable.

##################
# 2D Random Walk #
##################

import random
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation

xposition = [0]
yposition = [0]

def random_walk(i):
    polar_angle = random.random()*2*math.pi
    radius      = random.random()

    xposition.append( xposition[-1] + radius*math.cos(polar_angle) )
    yposition.append( yposition[-1] + radius*math.sin(polar_angle) )

    plt.plot( xposition, yposition, c = 'k')

animation = animation.FuncAnimation( fig = plt.figure(), func = random_walk,
                                     interval = 1000 )
plt.show()