Wiener process animated GIF with R
An easy look into animation with R by simulating Brownian motion and creating a GIF in a few steps. This post is based on Javi Fernandez Post “Brownian Motion GIF with R and ImageMagick”.
This is a modify version with a refactor functions to generate the simulated process and some minor fixes, but the overall process keeps the same core idea.
Let’s explore the concept of what Brownian motion is? Basically is the random motion of particles suspended in a liquid or gas (not very helpful right), there is an interesting story into how it came to be discovered by botanist Robert Brown and later describe by Einstein, but that is away from the scope of this humble post.
How the simulation works?
Well basically it uses the rnom
function to mimic the randomness of the motion, in fact I could argue that the proper title should be Wiener Process instead of Brownian motion as it explained more the core part of the data frame that is generated, although both of those term are correlated nonetheless. Here is a snipted of the functions that randomly generate data frame of motion:
Simple enough the core idea is to create a dataframe with a size of values such that by calling generate_random_process(0,5)
would output:
X | Y |
---|---|
1.49975518 | 1 |
0.35771348 | 2 |
0.58231513 | 3 |
-0.01806287 | 4 |
-1.07139526 | 5 |
Then is just a matter of plotting this simple X,Y coordinates into an R plot. A function to plotting all of the process showMotion
illustrate how to do it. But the goal is to create an animated gif so instead the procedure involves generated a set of images that will draw each process per step and save it.
Last but not least we paste this using the command “convert” from imagemagick tool.
Et voila! the result look like this: