跨块修改地块

Modifying plot across chunks

我正在尝试修改 re-display 后面代码块中的情节。我认为 knitrglobal.device 选项可以实现这一点。但是我想知道为什么当我在间歇性的幻灯片上执行一些代码时,最新的情节是 re-displayed。

我的header如下:

---
output:
  beamer_presentation
---

```{r setup, include=F, cache=F}
library(knitr)
opts_chunk$set(fig.width=4.5,
               fig.height=3,
               fig.align="center",
               echo=FALSE,
               cache=FALSE,
               eval=TRUE,
               message=FALSE)
knitr::opts_knit$set(global.device = TRUE)

然后我想要三张幻灯片:第一张显示散点图,第二张执行一些代码但不显示绘图,第三张修改绘图并再次显示。

# Slide 1

Display a scatter plot.

```{r scatter}
data(mtcars)
mpg <- mtcars$mpg
wt <- mtcars$wt
plot(mpg, wt)
```    

# Slide 2

Some R code is evaluated. But print only text.

```{r reg_estimates}
model <- lm(wt ~ mpg)
``` 

# Slide 3

Plot a modified graph and close it.

```{r abline}
abline(model, lwd = 2, col="red")
out <- dev.off()
```

令我困惑的是,幻灯片 1 的情节再次显示在幻灯片 2 上。我该如何防止这种情况?

global.device 将为每个中间块执行此操作。另一种方法是使用 recordPlotreplayPlot(均用于基本图形):

---
output:
  beamer_presentation
---

```{r setup, include=F, cache=F}
library(knitr)
opts_chunk$set(fig.width=4.5,
               fig.height=3,
               fig.align="center",
               echo=FALSE,
               cache=FALSE,
               eval=TRUE,
               message=FALSE)
# knitr::opts_knit$set(global.device = TRUE)
```

# Slide 1

Display a scatter plot.

```{r scatter}
data(mtcars)
mpg <- mtcars$mpg
wt <- mtcars$wt
plot(mpg, wt)
plt <- recordPlot()
```    

# Slide 2

Some R code is evaluated. But print only text.

```{r reg_estimates}
model <- lm(wt ~ mpg)
``` 

# Slide 3

Plot a modified graph and close it.

```{r abline}
replayPlot(plt)
abline(model, lwd = 2, col="red")
# out <- dev.off()
```