简体   繁体   中英

How to include multiple plot3d in markdown (knitr) under a loop

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.

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

Another solution is to include multiple rglwidget() values. You need to put them all in a call to htmltools::tagList() for this to work. (You won't need the rglwidget package if you use the development version of rgl from https://r-forge.r-project.org/R/?group_id=234 ). Modifying Vince's example,

---
output: html_document
---

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM