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

半世苍凉 提交于 2019-12-19 04:03:29

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/38664432/how-to-include-multiple-plot3d-in-markdown-knitr-under-a-loop

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