Tuesday, 18 October 2022

R: Adding a Search Bar to Plotly

I found this stackoverflow post over here (Highlight/find data points in plotly scatter from the browser) in which they show how to create a search bar for a scatterplot in plotly.

I tried to run the code provided in this example:

library(plotly)
library(htmlwidgets)
library(htmltools)

pcaCars <- princomp(mtcars, cor = TRUE)
carsHC <- hclust(dist(pcaCars$scores), method = "ward.D2")

carsDf <- data.frame(pcaCars$scores, "cluster" = factor(carsClusters))
carsClusters <- cutree(carsHC, k = 3)

carsDf <- transform(carsDf, cluster_name = paste("Cluster", carsClusters))

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

The code seems to run, but I do not see a search bar:

enter image description here

Can someone please show me what I am doing wrong and how I can fix this problem?

Thanks!



from R: Adding a Search Bar to Plotly

No comments:

Post a Comment