首页 > 解决方案 > 如何使用 knitr 在 Latex 投影仪中获取叠加动画?

问题描述

在latex beamer 中,您可以编写以下代码来获取叠加动画:

\begin{overprint}
  \foreach \x in {1,2,3}{%
    \only<\x>{%
      \includegraphics{figure/plot-\x.pdf}
    }
  }
\end{overprint}

我怎样才能knitr产生这样的输出并使用叠加动画?

PS:我知道,fig.out='animate'但它只适用于 Acrobat,而我想要一个通用的解决方案。

标签: latexknitrbeamer

解决方案


我能够编写一个chunk_hook扫描块输出并添加叠印环境以及\only<i>每个图周围的部分的代码:

这是钩子:

library(stringi)
overlay_hook = function(x, options) {
  x = knitr:::.chunk.hook.tex(x, options)
  if (!is.null(options$overlay_start)) {
    ind_matches = stri_locate_all_regex(x, "\\\\includegraphics")[[1]]
    stri_sub_all(x, from = ind_matches[,2]+1, length = 0) = 
      paste0("<", seq_len(nrow(ind_matches)) + options$overlay_start - 1 ,">")
  }
  return(x)
}
knitr::knit_hooks$set(chunk = overlay_hook)

要使用它,您必须设置overlay_start一个值(例如,如果它应该从第一个动画步骤开始,则为 1)

<<plot, results='hide', overlay_start = 1, fig.height=3>>=
for (i in 1:3)
  plot(function(x) x^i)
@

推荐阅读