Search code examples
pythonmatplotlibffmpegvisualizationstochastic-process

Animating a 2D plot (2D brownian motion) not working in Python


I am trying to plot a 2D Brownian motion in Python but my plot plots the grid but does not animate the line.

Attempted at performing this plot is below,

!apt install ffmpeg

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation


np.random.seed(5)


# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)


def generateRandomLines(dt, N):
    dX = np.sqrt(dt) * np.random.randn(1, N)
    X = np.cumsum(dX, axis=1)

    dY = np.sqrt(dt) * np.random.randn(1, N)
    Y = np.cumsum(dY, axis=1)

    lineData = np.vstack((X, Y))

    return lineData


# Returns Line2D objects
def updateLines(num, dataLines, lines):
    for u, v in zip(lines, dataLines):
        u.set_data(v[0:2, :num])

    return lines

N = 501 # Number of points
T = 1.0
dt = T/(N-1)


fig, ax = plt.subplots()

data = [generateRandomLines(dt, N)]

ax = plt.axes(xlim=(-2.0, 2.0), ylim=(-2.0, 2.0))

ax.set_xlabel('X(t)')
ax.set_ylabel('Y(t)')
ax.set_title('2D Discretized Brownian Paths')

## Create a list of line2D objects
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1])[0] for dat in data]


## Create the animation object
anim = animation.FuncAnimation(fig, updateLines, N+1, fargs=(data, lines), interval=30, repeat=True, blit=False)

plt.tight_layout()
plt.show()

## Uncomment to save the animation
#anim.save('brownian2d_1path.mp4', writer=writer)

However, instead of performing the plot the program is printing, enter image description here

How do I animate this plot? I am new to python so I apologize in advanced if this is an easy question.

I found this question on http://people.bu.edu/andasari/courses/stochasticmodeling/lecture5/stochasticlecture5.html , there is a walkthrough of how this code came to being.


Solution

  • Thanks to @JohanC 's help got it to work.

    #!apt install ffmpeg
    #!brew install imagemagick
    
    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt
    
    from matplotlib import animation, rc
    from IPython.display import HTML, Image # For GIF
    
    rc('animation', html='html5')
    np.random.seed(5)
    
    
    # Set up formatting for the movie files
    Writer = animation.writers['ffmpeg']
    writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
    
    
    def generateRandomLines(dt, N):
        dX = np.sqrt(dt) * np.random.randn(1, N)
        X = np.cumsum(dX, axis=1)
    
        dY = np.sqrt(dt) * np.random.randn(1, N)
        Y = np.cumsum(dY, axis=1)
    
        lineData = np.vstack((X, Y))
    
        return lineData
    
    
    # Returns Line2D objects
    def updateLines(num, dataLines, lines):
        for u, v in zip(lines, dataLines):
            u.set_data(v[0:2, :num])
    
        return lines
    
    N = 501 # Number of points
    T = 1.0
    dt = T/(N-1)
    
    
    fig, ax = plt.subplots()
    
    data = [generateRandomLines(dt, N)]
    
    ax = plt.axes(xlim=(-2.0, 2.0), ylim=(-2.0, 2.0))
    
    ax.set_xlabel('X(t)')
    ax.set_ylabel('Y(t)')
    ax.set_title('2D Discretized Brownian Paths')
    
    ## Create a list of line2D objects
    lines = [ax.plot(dat[0, 0:1], dat[1, 0:1])[0] for dat in data]
    
    
    ## Create the animation object
    anim = animation.FuncAnimation(fig, updateLines, N+1, fargs=(data, lines), 
    interval=30, repeat=True, blit=False)
    
    plt.tight_layout()
    plt.show()
    
    # Save as GIF
    anim.save('animationBrownianMotion2d.gif', writer='pillow', fps=60)
    
    Image(url='animationBrownianMotion2d.gif')
    ## Uncomment to save the animation
    #anim.save('brownian2d_1path.mp4', writer=writer)
    

    enter image description here