including a interactive 3D figure with knitr

Stéphane Laurent picture Stéphane Laurent · Feb 14, 2013 · Viewed 16.2k times · Source

Using knitr it is possible to embed a rgl 3D graphics in a html document from a Rmarkdown source file:

```{r setup}
library(rgl)
knit_hooks$set(rgl = hook_rgl)
x <- sort(rnorm(1000))
y <- rnorm(1000)
z <- rnorm(1000) + atan2(x,y)
```

```{r, rgl=TRUE}
plot3d(x, y, z, col=rainbow(1000))
```

But the 3D graphic is not interactive in the html document. Is it possible to get an interactive 3D graphic ? The writeWebGL() function of the rgl package creates a html file with an interactive 3D graphic, is there a way to include directly this html code with Rmarkdown ? Otherwise how to include this html code manually ?

Update 24/06/2013

Here is an example that does not work today (the 3D graphic does not appear in Chrome):

  • the Rmd source file, which is very basic:

    ```{r setup}
    library(rgl)
    knit_hooks$set(webgl = hook_webgl)
    ```
    ```{r, webgl=TRUE}
    M <- rbind(
      c(0,0,0),
      c(-1,4,0),
      c(4,9,0),
      c(6,3,0)
      )
      points3d(M,col='red')
    ```
    ```{r}
    sessionInfo()
    ```
    

    I have knitted this file with the RStudio "knit" button in two situations using different versions of rgl and knitr packages (but this is surely due to the rgl package because the problem occurs with the output of the writeWebGL function) :

  • old versions with R-2.15.2 : source file and html rendering. And the html file generated by writeWebGL with rgl_0.93.928. For me it works well (there are just 4 red points in the 3D plot... not easy to see on my dirty screen but I see them).

  • latest versions with R-2.15.3 : source file and html rendering. And the html file generated by writeWebGL with rgl_0.93.935. For me it doesn't work: the 3D plot is not visible. I use Windows 7 and it doesn't work with Chrome, neither with Firefox.

Edit 28/06/2013

The problem raised by the 24/06 update has nothing to do with knitr. I have rephrased it in this post: WebGL rendering with rgl 0.93.935 R package

Answer

Yihui Xie picture Yihui Xie · Feb 15, 2013

I added a new hook hook_webgl() in knitr, which was incorporated into rgl later. Here is an example:

```{r setup}
library(knitr)
library(rgl)
knit_hooks$set(webgl = hook_webgl)
```

```{r testgl, webgl=TRUE}
x <- sort(rnorm(1000))
y <- rnorm(1000)
z <- rnorm(1000) + atan2(x,y)
plot3d(x, y, z, col=rainbow(1000))
```