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:

  1. 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:

  1. ---
  2. title: "Using a global graphical device to record plots"
  3. ---
  4. First, turn on a global graphical device:
  5. ```{r, include=FALSE}
  6. knitr::opts_knit$set(global.device = TRUE)
  7. ```
  8. Draw a plot:
  9. ```{r}
  10. par(mar = c(4, 4, 0.1, 0.1))
  11. plot(cars)
  12. ```
  13. Add a line to the plot in the previous code chunk:
  14. ```{r}
  15. fit <- lm(dist ~ speed, data = cars)
  16. abline(fit)
  17. ```
  18. No longer use the global device:
  19. ```{r, include=FALSE}
  20. knitr::opts_knit$set(global.device = FALSE)
  21. ```
  22. Draw another plot:
  23. ```{r}
  24. plot(pressure, type = 'b')
  25. ```

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.