r - 禁用图例双击事件

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

最佳答案

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

  • 选择您的主要 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
    

关于r - 禁用图例双击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51877429/

相关文章:

r - 在R中使用设防功能时出错(ggplot)

r - write.csv 用于大数据.table

r - 如何在 ggplotly 中为条形图更改悬停背景颜色

octave - 如何减少 Octave 图例功能中的空白

r - 如何在 Leaflet for R 中基于 addLayerControl() 隐藏/切换图例

r - 选择排序与插入排序。速度差异巨大

r - 在 Shiny 中的 selectInput() 中应该怎么写?

python plotly smith 图表函数行为与 scikit-rf 不同

css - 从 html 中的交互式表格更新绘图

javascript - 是否有一种样式可以让图例将每个系列的样式设置为按钮?