2017-09-13 48 views
0

我有一个很少数据的线图。像这样的位:Plotly(r)显示点击一行的所有hoverinfos

plot_ly(x = c(-2, 0, 1.5),y = c(-2, 1, 2.2), type = 'scatter' ,mode = 'lines+markers') %>% 
add_trace(x=c(-1,0.4,2.5),y=c(2, 0, -1),type='scatter',mode='lines+markers') 

我想知道是否plotly可以在个位线的所有hoverinfos。例如,当我点击图例中的“迹线1”时,我可以看到它具有相应点旁边的点(-1,2),(0.4,0),(2.5,-1)。到目前为止找不到任何东西。

更新:由于我提出了一些编码错误,你可以在链接的帖子中看到我想要实现的应用程序。我在那里用shiny实现了我的想法。

回答

1

您可以使用Plotly.Fx触发悬停事件,并使用htmlwidgets添加必要的Javascript代码。

Fx.hover需要curveNumbercurvePoint(你的足迹ñ个)作为输入参数。如果您想要触发多点事件,则需要传递一组对象。

enter image description here

library("plotly") 
library("htmlwidgets") 

p <- plot_ly(x = c(-2, 0, 1.5), 
      y = c(-2, 1, 2.2), 
      type = 'scatter', 
      mode = 'lines+markers') %>% 
    add_trace(x = c(-1, 0.4, 2.5), 
      y = c(2, 0, -1), 
      type = 'scatter', 
      mode = 'lines+markers') %>% 
    layout(hovermode = 'closest') 

javascript <- " 
var myPlot = document.getElementsByClassName('plotly')[0]; 
myPlot.on('plotly_click', function(data) { 
    var hover = []; 
    for (var i = 0; i < data.points[0].data.x.length; i += 1) { 
    hover.push({curveNumber: data.points[0].curveNumber, 
       pointNumber: i}); 
    } 
    Plotly.Fx.hover(myPlot, hover); 
});" 
p <- htmlwidgets::prependContent(p, onStaticRenderComplete(javascript), data = list('')) 
p 

注:Plotly.Fxdeprecated

+1

基本上我们已经等待下一个剧情发布,以确定这个功能是否会被保留下来。我仍然会接受你的答案,因为在当前版本中(对于plotly.js和R-package为4.7.1)可能没有任何其他解决方案。我希望有些用户会在新版本发布时发表评论。 – 5th