Plotly (r) show all hoverinfos of a line on click

好久不见. 提交于 2019-12-25 17:07:09

问题


I have a line-plot with very little data. A bit like this:

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

I want to know whether plotly can display all the hoverinfos of a line at ones. Such that for example when I click on "trace 1" in the legend, I can see it has the points (-1,2), (0.4,0), (2.5,-1) beside the corresponding point. Couldn't find anything so far.


回答1:


You can trigger hover events with Plotly.Fx and add the necessary Javascript code by using htmlwidgets.

Fx.hover needs a curveNumber and curvePoint (the n-th of your trace) as input parameters. If you want to trigger events for multiple points, you need to pass an array of objects.

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

Note: Plotly.Fx will be deprecated.



来源:https://stackoverflow.com/questions/46199423/plotly-r-show-all-hoverinfos-of-a-line-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!