including a interactive 3D figure with knitr

柔情痞子 提交于 2019-11-26 17:34:59

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/14879210/including-a-interactive-3d-figure-with-knitr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!