How can I get Rmarkdown to include the plot from a window open source script?

I am using Rmarkdown in RStudio and including graphics opened in new graphics windows. If the window is opened directly in the code block, then it is included in the processed document. But if the window is opened by a separate script source, then the graph appears during the processing of Nitter, but not included in the document. Below is the complete minimal example .Rmd script to demonstrate:

---
title: "Rmarkdown graph inclusion"
---

# Make a simple plot:

```{r}
plot(0,0,main="Attempt 1")
```

Result of above: Plot is displayed during processing and is included in generated document.


# Make the plot in a separate graphics window:

```{r}
windows() # open new graphics window; x11() on Linux, MacOS
plot(0,0,main="Attempt 2")
```

Result of above: Plot is displayed during processing and is included in generated document.

# Make the plot in a separate graphics window called from another script:

```{r}
writeLines( "windows() ; plot(0,0,main='From File')" ,
            con="openWindowScript.R" )
source("openWindowScript.R")
```

Result of above: Plot **is** displayed during Knitr processing but is **NOT** included in the generated document. *Why not?*

I searched stackoverflow and elsewhere for an answer, but did not find it. Thanks in advance for the answers or pointers!

+4
source share
2 answers

dev.print() source, ( ) , . knit . , :

```{r}
writeLines( "windows() ; plot(0,0,main='From File')" ,
            con="openWindowScript.R" )
source("openWindowScript.R")

dev.print()
```

Linux, X11 , , -, , Windows ( , dev.print Windows ​​, ).

dev.print ( , ), - , . NULL , if .

, :

```{r echo=1:2}
writeLines( "windows() ; plot(0,0,main='Ta-Da!')" ,
            con="theScript.R" )
source("theScript.R")

if(!is.null(knitr::current_input())){
  deviceInfo <- dev.print()  
}
```

windows() (/ x11). Rmd

x11 <- windows <- function(...){invisible(NULL)}

windows x11 (... , ). / , fig.width fig.height. , x11/windows, grDevices::x11 ( windows) . , , windows, .

+1

. - openWindowScript.R, - .

openWindowScript.R :

```{r}
windows(); plot(0,0,main='From File')
```

, (, ), . , :

```{r}
windows()
plot(0,0,main='From File')
```

, , ? source - , -, . , knitr - : , code :

```{r}
writeLines( "windows() \n plot(0,0,main='From File')" ,
            con="openWindowScript.R" )
```

```{r, code = readLines("openWindowScript.R")}
```
+1

Source: https://habr.com/ru/post/1663408/


All Articles