将绘图调用拆分为多个块 [英] Splitting a plot call over multiple chunks

查看:97
本文介绍了将绘图调用拆分为多个块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个图的说明,我将基本上在第一个块中创建该图,然后描述该输出,并在第二个块中添加一个轴.

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.

但是,似乎每个块都在强制一个新的绘图环境,因此当尝试单独使用axis运行一个块时,我们会收到错误消息.观察:

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

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

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

这个问题相关-例如,我们可以排除second块,并在second_invisible块上设置echo = -1(这在我的应用程序中也不起作用,但是我不想这里的事情太复杂了

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)

是否没有可以发送到第一个块的选项,例如dev.hold?

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

推荐答案

您可以设置选项global.device打开持久性图形设备:

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

这篇关于将绘图调用拆分为多个块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆