3

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Annie
  • 681
  • 7
  • 14

2 Answers2

4

Another solution is to include multiple rglwidget() values. You need to put them all in a call to htmltools::tagList() for this to work. Modifying Vince's example,

---
output: html_document
---

```{r setup}
library(rgl)
```

```{r testgl}
x <- sort(rnorm(1000))
y <- rnorm(1000)
z <- rnorm(1000) + atan2(x,y)

cols <- c("red", "orange", "green", "blue", "purple")
result <- list()
for(i in 1:5){
    plot3d(x, y, z, col = cols[i])
    result[[i]] <- rglwidget()
}
htmltools::tagList(result)
```
user2554330
  • 37,248
  • 4
  • 43
  • 90
3

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

```{r setup}
library(knitr)
library(rgl)
```

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)
```
user2554330
  • 37,248
  • 4
  • 43
  • 90