Knitr overlay ray animations

I would like to create an animation in beams using the knitr package and the chunk fig.show='animate' , with the shapes overlapping rather than being replaced in the same way as \ multiinclude works by default.

The minimum non-working example is the following (Rnw file), where I would like each point to be added one by one to the existing graph in the animation.

 \documentclass{beamer} \usepackage{animate} \begin{document} \begin{frame}[fragile] <<fig.show='animate', fig.width=5, fig.height=5, size='tiny', out.width='.8\\linewidth', fig.align='center', echo=FALSE>>= x = 1:2 plot(x,x,type="n") for (i in 1:length(x)) { points(x[i],x[i]) } @ \end{frame} \end{document} 

From a look at the knitr user manual , it is indicated that there are two graph sources: plot.new() and grid.newpage() , but has a footnote to see ?recordPlot , so I tried to put recordPlot() after the points command (and also add a transparent background via par(bg=NA) , but that didn’t work, since only one plot was created.

A minimal working example is the following

 \documentclass{beamer} \usepackage{animate} \begin{document} \begin{frame}[fragile] <<fig.show='animate', fig.width=5, fig.height=5, size='tiny', out.width='.8\\linewidth', fig.align='center', echo=FALSE, fig.keep='all'>>= x = 1:2 plot(x,x,type="n") for (i in 1:length(x)) { for (j in 1:i) points(x[j],x[j]) } @ \end{frame} \end{document} 

but this seems redundant as each figure redraws the plot and all previous points.

Is there a way to get rid of the loop over j ? or any other way to overlay graphs in a bundle / scribe? If so, how can I change my code to make this happen?

+6
source share
1 answer

As explained in the graphical manual, only graphs from high-level build commands (e.g., plot.new() ) and full expressions are recorded. This means that if you have several plot changes at the lower level in the for-loop, these changes will not be written one after the other, because the for-loop is in only one R expression. This is shown in Figure 4 in the manual.

If you want to create animations from a for loop, there must be high-level build commands in the loop. Example 7 in the manual is an example.

In your case, you need to move the plot() call to the loop:

 x = 1:2 for (i in 1:length(x)) { plot(x, x, type = "n") points(x[1:i], x[1:i]) } 

Yes, it seems like a serious waste of resources, and the “natural” way is to add points one by one like you, instead of opening a new chart and drawing points from 1 to i , but there is no way to detect low-level graphic changes inside one R -expressions.

+5
source

All Articles