R Shiny flexdashboard中Plotly直方图悬停超链接点击失效求助
问题根因
Plotly 原生悬浮提示的触发逻辑有明确的范围限制:默认仅把对应条形图的图形区域判定为悬浮有效范围,只要鼠标从条形区域挪到弹出的提示浮层上,系统就会判定悬浮状态结束,立刻把提示浮层收走,根本留不出时间让用户点浮层里的超链接。之前查到的同类解决方案只适配了“点数据点直接跳链接”的场景,没覆盖“提示浮层里嵌可点链接、需要浮层能停住让用户操作”的需求,所以无法直接复用。
适配flexdashboard的落地方法
整套方法不用改动原有ggplot绘图逻辑,只需要调整3个环节就能实现“提示浮层不提前消失、里面的超链接能正常点击”的效果:
- 把tooltip文本拼接时用的
\n换行,换成HTML标签<br>,避免Plotly把里面的超链接当纯文本转义,渲染不出可点击的元素 - 调整Plotly的内置布局参数,给tooltip加固定白底边框,避免超链接文本和背景融在一起不好识别
- 补几行超轻量的JS交互逻辑,把tooltip浮层本身也划进悬浮有效范围,只有当鼠标同时离开条形区和tooltip浮层的时候,才自动把提示收走
可直接复用的修改后代码
library("data.table") library("dplyr") library("ggplot2") library("plotly") library("htmltools") term_id = c("label1", "label2") term_name = c("soap", "vanila") adjust_pvalue = c(0,0) freq = c(2,5) ratio = c("(2/95)", "(5/13)") pvalue = c(0,0) links = c("<a href='https://en.wikipedia.org/wiki/SOAP' target='_blank'>SOAP</a>, <a href='https://es.wikipedia.org/wiki/Jab%C3%B3n' target='_blank'>Jabon</a>", "<a href='https://en.wikipedia.org/wiki/Multilayer_perceptron' target='_blank'>MP</a>, <a href='https://es.wikipedia.org/wiki/Vanilla' target='_blank'>flower</a>") mytable = data.frame(term_id = term_id, term_name = term_name, adjust_pvalue = adjust_pvalue, freq = freq, ratio = ratio, pvalue = pvalue, links = links) p <- mytable %>% # 替换原有换行逻辑,适配HTML渲染 dplyr::mutate(text = paste0( "ID Number: ", term_id, "<br>", "Term: ", term_name, "<br>", "Gene Ratio: ", ratio, "<br>", "Adjust pvalue: ", adjust_pvalue, "<br>", "Common genes: ", links )) %>% ggplot(aes(x= freq , y= reorder(paste0("",term_id,": ",term_name,""), -adjust_pvalue), fill = adjust_pvalue, text=text)) + theme (text = element_text(size= 8)) + geom_bar(stat="identity", alpha=0.7) + scale_fill_gradientn(colours = rainbow(2), trans= "log") + theme(legend.position="right") + labs(title = "My Analysis", x = "Number", y = "", fill = "p.value") + theme(plot.title = element_text(size = 15), axis.title.x = element_text(size = 10), axis.title.y = element_text(size = 10), axis.text = element_text(angle = 0)) newgg <- ggplotly(p, tooltip="text") %>% config(mathjax = "cdn", toImageButtonOptions = list( format = "svg", filename = "myplot", width = 1000, height = 600 ) ) %>% # 优化tooltip视觉样式 layout(hoverlabel = list(bgcolor = "white", bordercolor = "#cccccc")) %>% # 给图表绑定tooltip锁定交互逻辑 htmlwidgets::onRender(" function(el, x) { $(document).on('mouseenter', '.hovertext', function() { $(this).data('locked', true); }); $(document).on('mouseleave', '.hovertext', function() { $(this).data('locked', false); // 延迟检测隐藏状态,避免鼠标快速划过的时候误触发隐藏 setTimeout(() => { if ($('.hovertext:visible').length === 0) { Plotly.relayout(el.id, {'hoverinfo': 'none'}); setTimeout(() => Plotly.relayout(el.id, {'hoverinfo': 'all'}), 100); } }, 100); }); } ") # 直接嵌入flexdashboard输出即可 newgg
实际交互效果
- 鼠标挪到条形上的时候,tooltip按正常逻辑弹出,里面的ID、基因比例、p值、超链接都会正常渲染
- 哪怕鼠标从条形移到tooltip面板上,面板也不会消失,可以正常点击里面的超链接
- 等鼠标同时离开条形和tooltip面板之后,提示会自动隐藏,不会遮挡其他图表区域的操作
内容的提问来源于stack exchange,提问作者Aurora González Vidal
相关产品推荐
相关产品推荐

