绘制(r)单击时显示一行的所有悬停信息 [英] Plotly (r) show all hoverinfos of a line on click
问题描述
我有一个线图,数据很少.像这样:
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')
我想知道plotly
是否可以将某行的所有hoverinfos显示为1.这样,例如,当我单击图例中的迹线1"时,我可以看到它在对应点旁边有点(-1,2),(0.4,0),(2.5,-1).到目前为止找不到任何东西.
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.
推荐答案
您可以使用Plotly.Fx
触发悬停事件,并使用htmlwidgets
添加必要的Javascript代码.
You can trigger hover events with Plotly.Fx
and add the necessary Javascript code by using htmlwidgets
.
Fx.hover
需要curveNumber
和curvePoint
(轨迹的 n -th)作为输入参数.如果要触发多个点的事件,则需要传递一个对象数组.
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
注意:Plotly.Fx
将被弃用.
Note: Plotly.Fx
will be deprecated.
这篇关于绘制(r)单击时显示一行的所有悬停信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!