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:
- Calling it directly in tags$script in R (tags$script(src = 'https://cdn.plot.ly/plotly-latest.min.js'))
- 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)