1

I'm trying to knit a plot in two different chunks in RStudio notebook.

Here's a minimal example:

---

title: "R Notebook"

output:

  pdf_document: default

  html_notebook: default

editor_options:

  chunk_output_type: console

---

```{r}

plot(y = 1:61, x = 1:87, type = "n")

```

intermission

```{r}

contour(y = 1:61, x = 1:87, z = volcano, add = TRUE)

```

When running it in RStudio, it fails with the error message of plot.new has not been called yet when using default settings. Changing chunk output type to console instead of inline fixes it.

However, when knitting, this setting has no effect and it always fails. It is as if the second chunk does not know about the existence of the first chunk.

How to fix it, so it knows to add contour to the plot from the first chunk?

Gimelist
  • 791
  • 1
  • 10
  • 25
  • I don't know if it is related to the error but second chunk has the same name as first chunk, it will cause an issue. – Yacine Hajji Dec 05 '22 at 09:24
  • Or you could store the plot in your first chunk as in the following example and then call it in your second chunk https://stackoverflow.com/questions/29583849/save-a-plot-in-an-object – Yacine Hajji Dec 05 '22 at 09:26
  • 1
    This section in the R Markdown Cookbook is exactly the solution: https://bookdown.org/yihui/rmarkdown-cookbook/global-device.html – Yihui Xie Dec 06 '22 at 05:36

1 Answers1

1

The following seems to work.
Storing your plot with pryr in first chunk then calling it in the second chunk and adding contour function.

---

title: "R Notebook"

output:

  pdf_document: default

  html_notebook: default

editor_options:

  chunk_output_type: console

---

```{r libraries, include=FALSE}

library(pryr)

```


```{r firstChunk}

a %<a-% plot(y = 1:61, x = 1:61, type = "n")

```

intermission

```{r secondChunk}

a
contour(y = 1:61, x = 1:87, z = volcano, add = TRUE)

```

enter image description here

Yacine Hajji
  • 1,124
  • 1
  • 3
  • 20