'RMarkdown: How to embed an 3D plot?
How to embed 3D plot (rgl) into a html created via knitr?
There are several older posts looking for similar outcome. However, when I run all the sample codes i found. The rgl-plot don´t get embedded into the html created with knitr, but appears in an external window while "knitting" and disappears when the html page appears.
What I´m looking for is a way to integrate the 3D plot into the resulting html. I don´t mind whether it remains interactive or becomes static.
The following example is taken from the R Markdown Cookbook: https://bookdown.org/yihui/rmarkdown-cookbook/rgl-3d.html
title: Embed 3D plots with rgl
output: html_document
---
Set up a hook to save **rgl** plots:
```{r, setup}
library(rgl)
knitr::knit_hooks$set(webgl = hook_webgl)
```
See if it works for this 3D plot after we enable the hook
via the chunk option `webgl = TRUE`:
```{r, test-rgl, webgl=TRUE}
x <- sort(rnorm(1000))
y <- rnorm(1000)
z <- rnorm(1000) + atan2(x,y)
plot3d(x, y, z, col = rainbow(1000))
```
Solution 1:[1]
What you did should work, but it's not the best way to embed rgl
graphics in a document.
The simplest way is to make a call to rglwidget()
where you want the current plot inserted. You can also use options(rgl.useNULL=TRUE)
to suppress the separate window that rgl
creates when it plots. For example,
---
title: Embed 3D plots with rgl
output: html_document
---
No need for a hook with `rgl` version >= 0.96.0, just call `rglwidget()`.
```{r, setup}
options(rgl.useNULL = TRUE) # Suppress the separate window.
library(rgl)
```
See it work for this 3D plot without the hook:
```{r}
x <- sort(rnorm(1000))
y <- rnorm(1000)
z <- rnorm(1000) + atan2(x,y)
plot3d(x, y, z, col = rainbow(1000))
rglwidget()
```
Version 0.102.21 or newer of rgl
makes it even simpler: rgl
plots can be made to appear under almost the same rules as base graphics plots, with just a call to rgl::setupKnitr(autoprint = TRUE)
at the beginning.
I said what you tried should work, and it does for me. Why not for you? It's hard to guess what went wrong, but the most likely thing is probably that your web browser doesn't have WebGL enabled, or you're using some old version of R or rgl
that has a bug in it. One simple workaround for a bad browser is to switch to a static plot; you could do that with your code by changing hook = hook_webgl
to hook = hook_rgl
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |