我正在使用knitrR 的包来生成一个LaTeX文档,该文档将文本与嵌入的R图和输出结合起来.
写这样的东西是很常见的:
We plot y vs x in a scatter plot and add the least squares line:
<<scatterplot>>=
plot(x, y)
fit <- lm(y~x)
abline(fit)
@
Run Code Online (Sandbox Code Playgroud)
哪个工作正常.(对于那些不熟悉knitr或Sweave,此回声胶乳逐字环境的代码,并输出,并且还增加了所完成的情节作为乳胶文档中的数字).
但现在我想写更详细的逐行评论,如:
First we plot y vs x with a scatterplot:
<<scatterplot>>=
plot(x, y)
@
Then we regress y on x and add the least squares line to the plot:
<<addline>>=
fit <- lm(y~x)
abline(fit)
@
Run Code Online (Sandbox Code Playgroud)
问题是现在有两个knitr代码块用于同一个图.第二个代码块addline失败,因为在第一个代码块中创建的绘图框对第二个代码块中的代码scatterplot不可见.从一个代码块到下一个代码块,绘图窗口似乎不是持久的.
有什么方法可以告诉我为第二个代码块knit()保持plot()活动创建的绘图窗口吗?
如果那是不可能的,我怎样才能在添加到现有图表的代码行上实现LaTeX风格的评论?
一天后
我现在可以看到之前已经提出过基本相同的问题,请参阅: 如何使用knitr中的网格逐步构建分层图?从2013年开始,从2016 年 拆分多个块的情节调用.2013年的另一个问题也非常相似: 如何使用没有原始降价输出的knitr块向图中添加元素?
您可以设置knitr::opts_knit$set(global.device = TRUE),这意味着所有代码块共享同一全局图形设备。一个完整的例子:
\documentclass{article}
\begin{document}
<<setup, include=FALSE>>=
knitr::opts_knit$set(global.device = TRUE)
@
First we plot y vs x with a scatterplot:
<<scatterplot>>=
x = rnorm(10); y = rnorm(10)
plot(x, y)
@
Then we regression y and x and add the least square line to the plot:
<<addline>>=
fit <- lm(y~x)
abline(fit)
@
\end{document}
Run Code Online (Sandbox Code Playgroud)