Splitting a plot call over multiple chunks

不羁岁月 提交于 2019-12-10 17:13:11

问题


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?


回答1:


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




回答2:


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)
```


来源:https://stackoverflow.com/questions/37189068/splitting-a-plot-call-over-multiple-chunks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!