Home > Mobile >  Why does FuncAnimation revert back to the origin?
Why does FuncAnimation revert back to the origin?

Time:04-14

I am trying to animate a sample path of Brownian motion by using FuncAnimation, but the animation keeps reverting back to the origin.

enter image description here

Here is my code.

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

# create the time interval and partition 
t = 2.5 
n = 100 

# How many sample paths?
path_amt = 2 

# Create a brownian sample path 
def bsp(t, n): 
    dB = np.sqrt(t / n) * np.random.normal(0, 1, size=n)
    B = np.zeros(n 1)
    B[1:] = np.cumsum(dB)
    return(B)

# Simulate "path_amt" sample paths 
def sample_paths(i, t ,n):
    BSP = np.zeros((i, n 1))
    for k in range(i):
        BSP[k,:] = bsp(t, n)  
    return(BSP)

B_paths = sample_paths(path_amt, t, n)

This part is essentially just coming up with two independent Browinan motions. Each Brownian motion is a 1-d array of length n 1. I then store the two brownian motions in a (2, n 1) array titled B_paths, so each row represents a brownian motion. Here is the code for the animation.

# Create the animation function for the sample path
x = []
y = []
t_axis = np.linspace(0, t, n 1)

fig, ax = plt.subplots()

ax.set_xlim(0, 3)
ax.set_ylim(-4, 4)

line, = ax.plot(0, 0)

def anim_func(i):
    x.append(t_axis[int(i * n / t)])
    y.append(B_paths[0][int(i * n / t)])

    line.set_xdata(x)
    line.set_ydata(y)
    return line,

animation = FuncAnimation(fig, func = anim_func, \
                frames = np.linspace(0, t, n 1), interval = 10) 

plt.show()

CodePudding user response:

Because the animation is looping. Once frame reaches t=2.5, then it starts over, but inside your anim_func you don't clear x, y.

You can either modify this function:

def anim_func(i):
    x.append(t_axis[int(i * n / t)])
    y.append(B_paths[0][int(i * n / t)])

    line.set_xdata(x)
    line.set_ydata(y)
    if i == t:
        x.clear()
        y.clear()
    return line,

Or set repeat=False in the FuncAnimation call.

  • Related