Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable the legend double click event

How do I disable the "Double click on legend to isolate one trace" interaction in plotly for R? I want a double click to just have the effect of two clicks.

Here is an example on how to do this with Javascript:

Plotly.newPlot('graph', [{
  y: [1, 2, 1]
}, {
  y: [3, 4, 2]
}])
.then(gd => {
  gd.on('plotly_legenddoubleclick', () => false)
})
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<body>
  <div id="graph"></div>
</body>

It uses gd.on('plotly_legenddoubleclick', () => false). I do not know how to translate this to R.

Example in R:

library(plotly)

plot_ly() %>%
  add_trace(y = c(1,2,1), x = c(1,2,3), mode= "graph")    %>%
  add_trace(y = c(3,4,2), x = c(1,2,3), mode= "graph")
like image 757
PascalIv Avatar asked Aug 16 '18 12:08

PascalIv


2 Answers

You could add similar JavaScript code to your R code by using htmlwidgets.

  • Select your mai-n Plotly DOM object
  • Overwrite the event listener
  • Add it to your R Plotly object

Notes:

  • Update Plotly to the latest developer version via devtools::install_github("ropensci/plotly")
  • If it doesn't work in RStudio, you'll need to export the graph as HTML

    library(plotly)
    library(htmlwidgets)
    
    p <- plot_ly() %>%
      add_trace(y = c(1,2,1), x = c(1,2,3), mode= "graph", type='scatter')    %>%
      add_trace(y = c(3,4,2), x = c(1,2,3), mode= "graph", type='scatter')
    
    javascript <- "var myPlot = document.getElementsByClassName('plotly')[0];
    myPlot.on('plotly_legenddoubleclick', function(d, i) {return false});"
    p <- htmlwidgets::prependContent(p, htmlwidgets::onStaticRenderComplete(javascript), data=list(''))
    p
    
like image 75
Maximilian Peters Avatar answered Oct 14 '22 23:10

Maximilian Peters


I don't think javascript is necessary for this anymore, if it was in 2018. You can achieve this outcome directly in R by setting the legend's itemdoubleclick attribute via layout():

library(plotly)

plot_ly() %>%
  add_trace(y = c(1,2,1), x = c(1,2,3), mode= "graph") %>%
  add_trace(y = c(3,4,2), x = c(1,2,3), mode= "graph") %>%
  layout(legend = list(itemdoubleclick = FALSE))
like image 32
lauren.marietta Avatar answered Oct 14 '22 23:10

lauren.marietta