我正在使用 R 的 knitr
包来生成一个将文本与嵌入的 R 绘图和输出相结合的 LaTeX 文档。
通常这样写:
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)
@
效果很好。 (对于那些不熟悉 knitr 或 Sweave 的人来说,这会在 LaTeX 逐字环境中回显代码和输出,并将完成的绘图添加为 LaTeX 文档中的图形。)
但现在我想写更详细的逐行评论,例如:
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)
@
问题是现在同一个图有两个 knitr
代码块。第二个代码块 addline
失败,因为在第一个代码块 scatterplot
中创建的绘图框对于第二个代码块中的代码不可见。绘图窗口似乎并不从一个代码块到下一个代码块持续存在。
有什么方法可以告诉 knit()
让 plot()
创建的绘图窗口在第二个代码块中保持事件状态吗?
如果这是不可能的,我还能如何在添加到现有绘图的代码行上实现 LaTeX 风格的注释?
一天后
我现在可以看到之前已经问过基本上相同的问题,请参阅: How to build a layered plot step by step using grid in knitr?从 2013 年起和 Splitting a plot call over multiple chunks从2016年开始。 2013年的另一个问题也非常相似: How to add elements to a plot using a knitr chunk without original markdown output?
最佳答案
您可以设置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}
关于r - knitr:添加到新代码块中的上一个绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47736500/