MichaelChirico
MichaelChirico

Reputation: 34703

Splitting a plot call over multiple chunks

I'm writing an explanation of a plot where I'll basically create the plot in a first chunk, then describe that output, and add an axis in a second chunk.

However, it seems each chunk forces a new plotting environment, so we get an error when trying to run a chunk with axis alone. Observe:

---
output: html_document
---

```{r first}
plot(1:10, 1:10, xaxt = "n")
```

Look, no x axis!

```{r second}
axis(side = 1, at = 1:10)
```

Error in axis(side = 1, at = 1:10) : plot.new has not been called yet Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> axis Execution halted

Obviously this is a valid workaround that has identical output:

---
output: html_document
---

```{r first}
plot(1:10, 1:10, xaxt = "n")
```

Look, no x axis!

```{r second, eval = FALSE}
axis(side = 1, at = 1:10)
```
 ```{r second_invisible, echo = FALSE}
plot(1:10, 1:10, xaxt = "n")
axis(side = 1, at = 1:10)
```

But this is less than ideal (duplicated code, having to evaluate the plot twice, etc.)

This question is related -- e.g., we could exclude the second chunk and set echo = -1 on the second_invisible chunk (this also wouldn't work in my application, but I don't want to over-complicate things here)

Is there no option like dev.hold that we can send to the first chunk?

Upvotes: 4

Views: 487

Answers (2)

Yihui Xie
Yihui Xie

Reputation: 30114

You can set an option global.device to open a persistent graphical device:

---
output: html_document
---

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

```{r first}
plot(1:10, 1:10, xaxt = "n")
```

Look, no x axis!

```{r second}
axis(side = 1, at = 1:10)
```

Upvotes: 2

user5359531
user5359531

Reputation: 3555

You might look into using recordPlot

---
output: html_document
---

```{r first}
plot(1:10, 1:10, xaxt = "n")
x<-recordPlot()
```

Look, no x axis!

```{r second}
replayPlot(x)
axis(side = 1, at = 1:10)

```

sources:

R: Saving a plot in an object

R plot without showing the graphic window

https://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/recordplot.html <- note the disclaimer about ggplot2 here

Upvotes: 2

Related Questions