Using plotly.js script in Rstudio instead of plotly library

I am creating an interactive 3D plot in a shiny app using the Plotly js script directly instead of the plotly library in R but it doesn't seem to be working. The reason I would like to use the Plotly js script is because Plotly R does not have the same methods/attributes that I used before in JS.

I have tried the following methods:

  1. Calling it directly in tags$script in R (tags$script(src = 'https://cdn.plot.ly/plotly-latest.min.js'))
  2. Creating a plotly-latest-min.js file in same directory and calling it from there (tags$script(src = "plotly-latest-min.js"))

Below is a sample code that I am hoping to run and read the plot elements to extract the necessary information that is otherwise hidden if I were to use the plotly library directly in R

library(shiny)
library(shinyjs)

x <- rnorm(100)
y <- rnorm(100)
z <- rnorm(100)

js_code <- "
 shinyjs.plot3d = function(mydiv, x, y, z) {
   var data = []

   data = [
     {
       opacity:1,
       type: 'scatter3d',
       mode: 'markers',

       x: x,
       y: y,
       z: z,
     }];

   var layout = {
     autosize: false,
     width: 800,
     height: 800,
     scene:{
       aspectmode: 'manual',
       aspectratio: {
         x: 1, y: 1, z: 1,
       }
   };

   var graphDiv3D = document.getElementById(mydiv);

   Plotly.newPlot(graphDiv3D, data, layout)
 }
 "

ui <- fluidPage(
  useShinyjs(),
  extendShinyjs(text = js_code, functions = c('plot3d')),
  tags$head(
    tags$script(src = "plotly-latest-min.js"),
    #tags$script(src = 'https://cdn.plot.ly/plotly-latest.min.js')
  ),
  tags$body(
    tags$div(id='mydiv', class = 'myplot')
  ),
  actionButton('show_plot_button', 'Show Test Plot'),
)

server <- function (input, output, session){
  
  observeEvent(input$show_plot_button,{
    plot = js$plot3d('mydiv',x, y, z)
    View(plot);
  })
  
  observeEvent(input$show_plot_button,{
    runjs('
          var plotElement = document.getElementById("mydiv");
          var camera=plotElement._fullLayout.scene._scene.glplot.cameraParams;
          var scene=gd3D._fullLayout.scene._scene;
          var dataScale=scene.dataScale;
          console.log(plotElement._fullLayout)
          console.log(camera)
          ')
  })
}

shinyApp(ui, server)

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.