禁用图例双击事件

时间:2018-08-16 12:45:06

标签: r plotly legend r-plotly

如何在R的绘图中禁用“双击图例以隔离一条痕迹”交互?我希望双击只产生两次单击的效果。

以下是有关如何使用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>

它使用gd.on('plotly_legenddoubleclick', () => false)。 我不知道如何将其翻译为R。

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")

2 个答案:

答案 0 :(得分:4)

您可以使用htmlwidgets将类似的JavaScript代码添加到R代码中。

  • 选择您的mai-n Plotly DOM对象
  • 覆盖事件监听器
  • 将其添加到您的R Plotly对象中

注意:

  • 通过devtools::install_github("ropensci/plotly")
  • 将Plotly更新到最新的开发人员版本。
  • 如果在RStudio中不起作用,则需要将图形导出为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
    

答案 1 :(得分:0)

如果是在 2018 年,我认为不再需要 javascript。您可以通过 layout() 设置图例的 itemdoubleclick 属性,直接在 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") %>%
  layout(legend = list(itemdoubleclick = FALSE))