0

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.

user4933
  • 1,485
  • 3
  • 24
  • 42
  • 1
    On my system (pycharm under Windows) it works after removing `matplotlib.use("Agg")` and `writer = Writer(...`. And adding `import numpy as np`. – JohanC Apr 08 '20 at 19:29
  • Thanks at JohanC, I did the same and seems to work, my problem now is it is saving well as a GIF but not showing as a GIF in the notebook. – user4933 Apr 08 '20 at 20:13

1 Answers1

0

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

user4933
  • 1,485
  • 3
  • 24
  • 42