The function brownian.motion() has illustrated the phenomenon of Random Walk on the 2D plane. For a point (x, y), its next location is (x + rnorm(1), y + rnorm(1)).
# create an HTML animation page of Brownian Motion # store the old option to restore it later oopt = ani.options(interval = 0.05, nmax = 100, ani.dev = png, ani.type = "png", title = "Demonstration of Brownian Motion", description = "Random walk on the 2D plane: for each point (x, y), x = x + rnorm(1) and y = y + rnorm(1).") ani.start() opar = par(mar = c(3, 3, 1, 0.5), mgp = c(2, .5, 0), tcl = -0.3, cex.axis = 0.8, cex.lab = 0.8, cex.main = 1) brownian.motion(pch = 21, cex = 5, col = "red", bg = "yellow") par(opar) ani.stop() ani.options(oopt)
The animation is like this:
If you use the lattice package, don't forget to print() your plots, otherwise graphics devices like png()
will not be able to record your images. Here is an example:
library(animation) library(lattice) bm.mat = data.frame(x = rnorm(10), y = rnorm(10)) oopt = ani.options(interval = 0.05, nmax = 100, title = "Demonstration of Brownian Motion", description = "Random walk on the 2D plane: for each point (x, y), x = x + rnorm(1) and y = y + rnorm(1).") ## Brownian Motion in lattice for (i in 1:ani.options("nmax")) { print(xyplot(y ~ x, bm.mat, xlim = c(-10, 10), ylim = c(-10, 10), pch = 19)) bm.mat = bm.mat + data.frame(x = rnorm(10), y = rnorm(10)) } ani.stop() ani.options(oopt)