der_radler
der_radler

Reputation: 579

Rendering 3d plots in R shiny markdown

I have a running code for a shiny markdown file. The plot i am trying is a 3d plot to be rendered as a shiny markdown document and not as an APP.

The code works but the 3d plot pops up in a new window and does not render it in the html.

Here is a reproducible example.

---
title: "test"
date: "April 16, 2019"
output: html_document
runtime: shiny
---
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(fig.pos = 'H')
library(kableExtra)
library(rgl) # plot3d
library(knitr)
library(shiny)
knit_hooks$set(webgl = hook_webgl, rgl = hook_rgl)

inputPanel(selectInput('x', label = 'x axis:', choices = colnames(mtcars)[1:7], selected = 'mpg'), 
           selectInput('y', label = 'y axis:', choices = colnames(mtcars)[1:7], selected = 'cyl'),
           selectInput('z', label = 'z axis:', choices = colnames(mtcars)[1:7], selected = 'hp'))

renderPlot({
  plot3d(mtcars[, input$x], mtcars[,input$y], mtcars[,input$z],
         size = 4, 
         xlab = paste('Feat. ', input$x, sep = ''), 
         ylab = paste('Feat. ', input$y, sep = ''),
         zlab = paste('Feat. ', input$z, sep = ''), 
         type = 'p', col = rainbow(3)
                      )
  rglwidget()

})


Output

enter image description here

enter image description here

Any clues what i am missing here ?

Many Thanks.

Upvotes: 0

Views: 413

Answers (1)

Stéphane Laurent
Stéphane Laurent

Reputation: 84529

Should be doable with rgl. Alternatively, you can use r3js.

---
title: "Untitled"
author: "Stéphane Laurent"
date: "2023-10-09"
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(r3js)
```

```{r}
inputPanel(
  selectInput(
    'x', label = 'x axis:', choices = colnames(mtcars)[1:7], selected = 'mpg'
  ), 
  selectInput(
    'y', label = 'y axis:', choices = colnames(mtcars)[1:7], selected = 'cyl'
  ),
  selectInput(
    'z', label = 'z axis:', choices = colnames(mtcars)[1:7], selected = 'hp')
)
```

```{r}
p <- reactive({
  plot3js(
    x = mtcars[, input$x], y = mtcars[,input$y], z = mtcars[,input$z],
    col = rainbow(3),
    xlab = input$x,
    ylab = input$y,
    zlab = input$z
  )})
renderR3js(r3js(p(), zoom = 3))
```

enter image description here

See the doc for the options.

enter image description here

Upvotes: 0

Related Questions