2014-09-19 63 views
4

以下R-减价代码不与Knitr工作:重用图形设备

Create a bimodal toy distribution. 

```{r} 
a = c(rnorm(100, 5, 2), rnorm(100, 15, 3)) 
``` 

Set up the graphics device. 

```{r fig.show='hide'} 
plot(0, type = 'n', xlim = c(0, 20), ylim = c(0, 0.2), axes = FALSE) 
``` 

Plot the density. 

```{r} 
polygon(density(a), col = 'black') 
``` 

Knitr假设一个图形设备在的R代码块的结尾处结束,并且关闭装置。因此,我不能重用(在第三个代码块中)以前设置的图形设备。

我的问题很简单:我该如何做这项工作?

回答

3

您可以通过recordPlot()保留上一幅图,并使用replayPlot()重绘。这可以在自定义块钩子函数中完成。下面是一个简单的例子:

```{r setup} 
library(knitr) 
knit_hooks$set(plot.reuse = local({ 
    last = NULL 
    function(before, options) { 
    if (!isTRUE(options$plot.reuse)) { 
     last <<- NULL 
     return(NULL) 
    } 
    if (before) { 
     if (inherits(last, 'recordedplot')) replayPlot(last) 
    } else { 
     last <<- recordPlot() 
    } 
    return(NULL) 
    } 
})) 
``` 

Draw a plot. 

```{r test-a, plot.reuse=TRUE} 
plot(cars) 
``` 

Add a line to the previous plot: 

```{r test-b, plot.reuse=TRUE} 
abline(lm(dist~speed, data=cars)) 
``` 

您也可以使用无证功能opts_knit$set(global.device = TRUE)使整个文件总是使用相同的图形设备,这是永远不会关闭。我从来没有在公众面前提到过这个功能,尽管它在那里已经有两年了,因为我没有仔细考虑过这种方法可能出现的意外后果。

-2

从我的理解,第一个情节是独立于第二个。

```{r} 
plot(0, type = 'n', xlim = c(0, 20), ylim = c(0, 0.2), axes = FALSE) 
polygon(density(a), col = 'black') 
``` 
+2

我知道。我明确想知道如何防止这种情况。 – 2014-09-19 10:52:05

1

这不是真正的解决方案,而是一种解决方法:我使用ggplot,因此我可以将图存储在变量中。由于变量在代码块之间共享,因此可以在后续代码块中重新使用部分完整的对象。