Annie - 9 months ago 87

R Question

I am plotting a 3d graph using plot3d {rgl} in a loop. knitr rgl hooks works fine for single 3d graph but when used in a loop, markdown file doesn't include 3d graphs. Any help?

Answer

One way you can do it is to use `mfrow3d()`

to put multiple "subscenes" in a single "scene", then use the `rglwidget()`

command to show the scene in your html. See more information here. Below is a heavily modified version of the script from Yihui's answer:

```
---
output: html_document
---
You will need to install the rglwidget library if you have not already.
```{r setup}
library(knitr)
library(rgl)
library(rglwidget)
```
Using mfrow3d() I create a scene with 5 subscenes,
so each of the 5 plots will appear in a single scene.
Each will still be independently interactive (can zoom in on one at a time, e.g.).
```{r testgl}
x <- sort(rnorm(1000))
y <- rnorm(1000)
z <- rnorm(1000) + atan2(x,y)
mfrow3d(nr = 5, nc = 1)
cols <- c("red", "orange", "green", "blue", "purple")
for(i in 1:5){
plot3d(x, y, z, col = cols[i])
}
rglwidget(height = 4000, width = 1000)
```
```