2017-09-13 50 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