3

Using code from a previous post I was able to add a search bar that highlights specific points on a scatter plot in plotly using R, which worked well in 2 dimensions. However, I have now produced a 3 dimensional plot with the same data and the code for the search bar no longer works. Is it possible to have a search bar in a 3 dimensional plot, and if so is there a way to alter the following code to achieve that?

p <- plot_ly(carsDf, x = ~Comp.1 , y = ~Comp.2, text = rownames(carsDf),
         mode = "markers", color = ~cluster_name, marker = list(size = 11), type = 'scatter', mode = 'markers')

p <- htmlwidgets::appendContent(p, htmltools::tags$input(id='inputText', value='Merc', ''), htmltools::tags$button(id='buttonSearch', 'Search'))
p <- htmlwidgets::appendContent(p, htmltools::tags$script(HTML(
'document.getElementById("buttonSearch").addEventListener("click", function()
{        
  var i = 0;
 var j = 0;
  var found = [];
  var myDiv = document.getElementsByClassName("js-plotly-plot")[0]
  var data = JSON.parse(document.querySelectorAll("script[type=\'application/json\']")[0].innerHTML);
  for (i = 0 ;i < data.x.data.length; i += 1) {
    for (j = 0; j < data.x.data[i].text.length; j += 1) {
      if (data.x.data[i].text[j].indexOf(document.getElementById("inputText").value) !== -1) {
        found.push({curveNumber: i, pointNumber: j});
      }
    }
  }
  Plotly.Fx.hover(myDiv, found);
}  
);'))) 
htmlwidgets::saveWidget(p, paste('pca', ".html", sep=""))
p                                                   

Thanks

JohnDoe999
  • 31
  • 3

0 Answers0