R Plotly共享Y轴子图如何关联轨迹实现悬停时双图同步显示hoverinfo
实现方案
核心逻辑
你要的关联悬停效果可以通过自定义JavaScript事件监听实现,不需要依赖Plotly原生的图例分组功能:
- 两个共享Y轴的子图,相同索引位置的点对应同一类别,只要监听到任意点的悬停事件,就主动触发所有子图对应索引位置的点的悬停提示即可
- 用
htmlwidgets::onRender()函数向Plotly图表注入JS代码即可实现
完整修改代码
你只需要在原有代码的基础上,补充最后注入JS的部分即可:
# 加载依赖包 library(plotly) library(htmlwidgets) custom_hover_t <- "%{x:.2f}%" custom_hover_c <- "%{x:.2f}%" t <- plot_ly(data = datos) %>% #Barras tamaño add_trace(x = ~T2019, y = ~EjeX, type = 'bar', width = 0.02, marker = list(color = ~color), orientation = "h", hoverlabel = list(bordercolor="white"), hovertemplate = custom_hover_t ) %>% add_trace(x = ~T2019, y = ~EjeX, type = 'scatter',mode = "markers", marker = list(color = ~color, size = 7), hoverlabel = list(bordercolor="white"), hovertemplate = custom_hover_t ) %>% plotly::layout( xaxis = list(title = NULL, autorange = T, zeroline = T, showline = F, autotick = FALSE, tickmode = "array", showgrid = T, showticklabels = F, titlefont = list(color="transparent") ), yaxis = list(title = NULL, visible = FALSE, autorange = TRUE, zeroline = FALSE, showline = F, showgrid = FALSE, ticklen = 0, titlefont = list(color="transparent") ), showlegend = F ) c <- plot_ly(data = datos) %>% #Barras tamaño add_trace(x = ~CambioRel, y = ~EjeX, type = 'bar', width = 0.02, marker = list(color = ~color), orientation = "h", hoverlabel = list(bordercolor="white"), hovertemplate = custom_hover_c ) %>% add_trace(x = ~CambioRel, y = ~EjeX, type = 'scatter',mode = "markers", marker = list(color = ~color, size = 7), hoverlabel = list(bordercolor="white"), hovertemplate = custom_hover_c ) %>% plotly::layout( xaxis = list(title = NULL, autorange = T, zeroline = T, showline = F, autotick = FALSE, tickmode = "array", showgrid = T, showticklabels = F, titlefont = list(color="transparent") ), yaxis = list(title = NULL, visible = FALSE, autorange = TRUE, zeroline = FALSE, showline = F, showgrid = FALSE, ticklen = 0, titlefont = list(color="transparent") ), showlegend = F ) fig <- subplot(t, c, shareY = TRUE) # 新增:注入JS实现关联悬停 fig <- fig %>% onRender(" function(el) { const plot = el; // 监听悬停事件 plot.on('plotly_hover', function(data) { const pointIndex = data.points[0].pointIndex; // 填写所有需要同步悬停的轨迹索引,当前场景共4条轨迹:子图1的bar、scatter,子图2的bar、scatter const traceIndices = [0, 1, 2, 3]; const hoverPoints = traceIndices.map(traceIdx => ({ curveNumber: traceIdx, pointNumber: pointIndex })); // 批量触发所有对应点的悬停提示 Plotly.Fx.hover(plot, hoverPoints); }); // 可选:监听移出事件,同步隐藏所有提示 plot.on('plotly_unhover', function() { Plotly.Fx.unhover(plot); }); } ") fig
调整说明
如果后续你修改了图表的轨迹数量、顺序,只需要更新traceIndices数组里的轨迹编号,把所有需要同步悬停的轨迹序号都放入数组即可。
内容的提问来源于stack exchange,提问作者Ainhoa
相关产品推荐
相关产品推荐

