14.5 Modify a plot in a previous code chunk

By default, knitr opens a new graphical device to record plots for each new code chunk. This brings a problem: you cannot easily modify a plot from a previous code chunk, because the previous graphical device has been closed. This is usually problematic for base R graphics (not so for grid graphics such as those created from ggplot2 (Wickham, Chang, et al. 2020) because plots can be saved to R objects). For example, if we draw a plot in one code chunk, and add a line to the plot in a later chunk, R will signal an error saying that a high-level plot has not been created, so it could not add the line.

If you want the graphical device to remain open for all code chunks, you may set a knitr package option in the beginning of your document device:

knitr::opts_knit$set(global.device = TRUE)

Please note that it is opts_knit instead of the more frequently used opts_chunk. You may see the Stack Overflow post https://stackoverflow.com/q/17502050 for an example.

When you no longer need this global graphical device, you can set the option to FALSE. Here is a full example:

---
title: "Using a global graphical device to record plots"
---

First, turn on a global graphical device:

```{r, include=FALSE}
knitr::opts_knit$set(global.device = TRUE)
```

Draw a plot:

```{r}
par(mar = c(4, 4, 0.1, 0.1))
plot(cars)
```

Add a line to the plot in the previous code chunk:

```{r}
fit <- lm(dist ~ speed, data = cars)
abline(fit)
```

No longer use the global device:

```{r, include=FALSE}
knitr::opts_knit$set(global.device = FALSE)
```

Draw another plot:

```{r}
plot(pressure, type = 'b')
```

References

Wickham, Hadley, Winston Chang, Lionel Henry, Thomas Lin Pedersen, Kohske Takahashi, Claus Wilke, Kara Woo, Hiroaki Yutani, and Dewey Dunnington. 2020. Ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics. https://CRAN.R-project.org/package=ggplot2.