<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/creating-an-animation-using-r/"></div></div><div><a data-url="https://www.r-bloggers.com/creating-an-animation-using-r/" data-counturl="https://www.r-bloggers.com/creating-an-animation-using-r/" data-count="horizontal" data-text="Creating an animation using R" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://datascienceplus.com/creating-an-animation-using-r/"> DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>In this post, I will show you how to create an animation using R and <a target="_blank" rel="nofollow" href="http://ffmpeg.org/">ffmpeg</a>. The idea to do so is pretty simple:</p>
<blockquote><ul>
<li>Generate a number of snapshots</li>
<li>Combine them in a video file using <a target="_blank" rel="nofollow" href="http://ffmpeg.org/">ffmpeg</a> </li>
</ul>
</blockquote>
<p>The best way to learn about the art of animation is by doing it ourselves, so our work example is the infamous <a target="_blank" rel="nofollow" href="http://mathoverflow.net/questions/2014/if-you-break-a-stick-at-two-points-chosen-uniformly-the-probability-the-three-r">Broken Stick Problem</a>. </p>
<p>Here is the scenario:<br>
Let there be a stick of length 1. Pick two points uniformly at random along the stick and break the stick at those points. What is the probability of the three resulting pieces being able to form a triangle? In the first part of this post, I will provide my analytical approach to calculate the probability. Then in the second part, I will use Monte Carlo simulation to reach to the answer.</p>
<h2>Analytical Solution</h2>
<p>The triangle inequality states that for any triangle, the sum of the lengths of any two sides must be greater than the length of the remaining side. Let’s suppose that \(X_2 > X_1\), the vertices of our triangle could have the following lengths: \(X_1\text{; } X_2 – X_1 \text{ and } 1 – X_2\). For the three pieces to form a triangle, none of them should have a length less than half. In order words the following conditions must be satisfied: (a) \(X_1 &lt; \dfrac{1}{2}\) (b) \(X_2 – X_1 &lt; \dfrac{1}{2}\) (c) \(1 – X_2 &lt; \dfrac{1}{2}\) (d) Sum of the 3 vertices is equal to 1.</p>
<p>The above conditions could also be established for the case where \(X_1 > X_2\). The diagram below displays the above conditions. Our areas of interest are derived by finding the intersection where conditions (a)-(d) are valid, hence giving us the probability of obtaining a triangle under such conditions.</p>
<p><a title="" data-rel="lightbox-0" target="_blank" href="https://i0.wp.com/datascienceplus.com/wp-content/uploads/2016/09/triangle.jpg"><img alt="Solution Triangle" class="wp-image-4651" src="https://i2.wp.com/datascienceplus.com/wp-content/uploads/2016/09/triangle-490x248.jpg?resize=456%2C217" data-recalc-dims="1"></a></p>
<p>Looking at the two areas (red and blue) above, the probability of obtaining a triangle is:</p>
<p>\(P(triangle) = Area(X_1 > X_2) + Area(X_2 > X_1) = 1/8 + 1/8 = 1/4\)</p>
<h2>Simulated Solution</h2>
<p>The estimation of the probability is done using a Monte Carlo algorithm. Here is my proposed approach to solve this problem:</p>
<ul>
<li>Generate 2 random points from a uniform distribution between 0 &amp; 1</li>
<li>Check whether the 2 two values obtained satisfy conditions (a)-(d); if yes give 1 to that pair otherwise give 0</li>
<li>Compute the cumulative empirical probability </li>
<li>Repeat the above steps multiple times (in this case 1000 times)</li>
</ul>
<p>The R-code is as follows:</p>
<pre>
suppressPackageStartupMessages(require(ggplot2))
set.seed(2016)
index_Score &lt;- function(){
  # Picking 2 points randomly on the stick at the same time
  x &lt;- runif(n = 2, min = 0, max = 1) 
  a &lt;- min(x) # first point
  b &lt;- max(x) # second point
  # pieces of the stick with their respective length
  pieces &lt;- c(a, b-a, 1-b)
  cond1 &lt;- sum(pieces[c(1,2)]) > pieces[3] # condition # 1
  cond2 &lt;- sum(pieces[c(1,3)]) > pieces[2] # condition # 2
  cond3 &lt;- sum(pieces[c(3,2)]) > pieces[1] # condition # 3
  combine_conds &lt;- ifelse(cond1 &amp; cond2 &amp; cond3, 1, 0) # if all 3 conditions are satisfied
  return(combine_conds)
}

cnt &lt;- c()
total &lt;- 1000
for(k in 1:total) cnt = c(cnt, index_Score())
df &lt;- setNames(data.frame(1:total, rep(0, total)), c(&quot;Incrmt&quot;,&quot;Probs&quot;))
for (i in 1:total)  df$Probs[i] &lt;- sum(cnt[1:i])/i
</pre>
<p>The final step consists of generating the snapshots (1000 of them) depicting the iterations and the cumulative probabilities and encoding these images into a video format. </p>
<pre>
for(i in 1:total) {
  sub_df &lt;- subset(df, df$Incrmt &lt;= i)
  simul_plot &lt;- qplot(Incrmt, Probs, data = sub_df, geom = &quot;path&quot;) + 
    labs(x = &quot;iterations&quot;, y = &quot;Probabilities&quot;, title = &quot;Monte Carlo Simulation&quot;) + ylim(c(0,0.4)) + 
    geom_hline(yintercept = 0.25, colour = &quot;red&quot;, linetype = &quot;longdash&quot;)
  ggsave(plot = simul_plot, filename = paste(sprintf(&quot;images/brokenstick_%02d&quot;,i),&quot;.png&quot;, sep = &quot;&quot;), limitsize = FALSE)
  rm(sub_df)
  dev.off()
}
</pre>
<p><a target="_blank" rel="nofollow" href="http://ffmpeg.org/">ffmpeg</a> is quite a nice tool which can be installed in Linux, Windows and Mac OS. The following command line in a terminal shell produces a video file in the mpeg format</p>
<pre>ffmpeg -r 10 -i broken_stick_%02d.png -b:v 20M BrokenStick_video.mp4</pre>
<p><code>-r 10</code> controls the rate of frames per seconds (10 fps here) and <code>-b:v 20M</code> sets the bitrate in the output file. </p>
<p>The result is the following video<br>
<iframe title="Monte Carlo Simulation - Broken Stick" height="500" width="500" allowfullscreen src="https://player.vimeo.com/video/182208608"></iframe><br>
And voila! Done.</p>
<p>When it comes to rendering great animations either to understand the dynamic behind data or just to impress your manager and /or colleagues, R provides multiples options to do so. The best R-package for animations that I would recommend is <a target="_blank" rel="nofollow" href="https://cran.r-project.org/web/packages/animation/index.html">animation</a> which provides functions to save animations in Flash, GIF, HTML pages, PDFs and videos.<br>
If you have enjoyed this post, please drop me some comments/suggestions.</p>
<p><small>P.S.: the background music is by <em>Nas – The World Is Yours (Instrumental)</em> produced by Pete Rock</small></p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a title="Permanent Link toThe importance of Data Visualization" target="_blank" rel="bookmark" href="http://datascienceplus.com/the-importance-of-data-visualization/">The importance of Data Visualization</a></li>
<li><a title="Permanent Link toggplot2 themes examples" target="_blank" rel="bookmark" href="http://datascienceplus.com/ggplot2-themes-examples/">ggplot2 themes examples</a></li>
<li><a title="Permanent Link toMap the Life Expectancy in United States with data from Wikipedia" target="_blank" rel="bookmark" href="http://datascienceplus.com/map-the-life-expectancy-in-united-states-with-data-from-wikipedia/">Map the Life Expectancy in United States with data from Wikipedia</a></li>
<li><a title="Permanent Link toWhat can we learn from the statistics of the EURO 2016 – Application of factor analysis" target="_blank" rel="bookmark" href="http://datascienceplus.com/what-can-we-learn-from-the-statistics-of-the-euro-2016-application-of-factor-analysis/">What can we learn from the statistics of the EURO 2016 – Application of factor analysis</a></li>
<li><a title="Permanent Link toVisualizing obesity across United States by using data from Wikipedia" target="_blank" rel="bookmark" href="http://datascienceplus.com/visualizing-obesity-across-united-states-by-using-data-from-wikipedia/">Visualizing obesity across United States by using data from Wikipedia</a></li>
</ol></strong>
<div>
<a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=rq3LoVaqiwA:WacRfO93AuM:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/datascienceplus?i=rq3LoVaqiwA:WacRfO93AuM:D7DqB2pKExk" border="0"></a> <a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=rq3LoVaqiwA:WacRfO93AuM:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=qj6IDK7rITs" border="0"></a> <a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=rq3LoVaqiwA:WacRfO93AuM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=yIl2AUoC8zA" border="0"></a>
</div>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/creating-an-animation-using-r/"></div></div><div><a data-url="https://www.r-bloggers.com/creating-an-animation-using-r/" data-counturl="https://www.r-bloggers.com/creating-an-animation-using-r/" data-count="vertical" data-text="Creating an animation using R" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://datascienceplus.com/creating-an-animation-using-r/"> DataScience+</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/gtrZrSpWSDQ"></a></div>