在多个块上拆分绘图调用

时间:2016-05-12 13:54:54

标签: r knitr

我正在写一个情节的解释,我将基本上在第一个块中创建绘图,然后描述该输出,并在第二个块中添加一个轴。

但是,似乎每个块都会强制建立一个新的绘图环境,因此我们在尝试单独使用axis运行块时会出错。观察:

---
output: html_document
---

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

Look, no x axis!

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

axis(side = 1, at = 1:10)中的错误:plot.new尚未被调用   来电:<Anonymous> ... withCallingHandlers - &gt; withVisible - &gt; eval - &gt; eval - &gt; axis   执行暂停

显然,这是一个有效的解决方法,它具有相同的输出:

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

但这不太理想(重复的代码,必须两次评估情节等)

This问题是相关的 - 例如,我们可以排除second块并在echo = -1块上设置second_invisible(这也不会起作用)我的申请,但我不想在这里过于复杂的事情)

我们可以发送到第一个大块没有像dev.hold这样的选项吗?

2 个答案:

答案 0 :(得分:2)

您可以考虑使用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)

```

来源:

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&lt; - 请注意关于ggplot2的免责声明

答案 1 :(得分:2)

您可以设置选项global.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)
```