注意:很遗憾,我还没有解决您的问题,但希望这些信息对您有所帮助。祝你好运!
背景:SVG
plotly
将绘图创建为Scalable Vector Graphics ( <svg>
)
工具提示<svg>
必须添加为名为的子元素<title>
<title>
应该是其父元素的第一个子元素
<svg>
需要在 SVG 命名空间中创建新元素
SVG 工具提示:矩形与绘图 x 轴
作为概念证明,我<svg>
在您的示例中添加了一个矩形。然后,我使用 JS 添加了一个<title>
元素作为该元素的第一个子<rect>
元素,这会在矩形上生成一个工具提示。

但是,对热图执行相同的步骤plotly
不会在 x 轴标题上生成工具提示,尽管<title>
元素已添加到 x 轴标题容器中。

代码
library(shiny)
library(plotly)
x <- y <- 1:10
dat <- expand.grid(x=x, y=y)
dat <- transform(dat, z=x*y)
### Create a <svg> rectangle element
testRect <- '<svg width="250" height="75" xmlns="http://www.w3.org/2000/svg">
<g class="test-rect">
<rect x="10" y="10" width="200" height="50"
style="fill:wheat; stroke:blue; stroke-width:1px"/>
</g>
</svg>'
### Add a first child title element to the rectangle <svg>
### Hovering over the rectangle displays the tooltip
jscode_testRect <- '$(document).ready(function(){
setTimeout(function(){
var titleRect = document.createElementNS("http://www.w3.org/2000/svg", "title");
titleRect.textContent = "rectangle tooltip";
var testRect = document.getElementsByClassName("test-rect")[0];
testRect.insertBefore(titleRect, testRect.childNodes[0]);
}, 500);
});'
### Add a first child title element to the SVG
### Hovering over the x-axis title doesn't display tooltip
jscode_xaxisPlotly <- '$(document).ready(function(){
setTimeout(function(){
var titleAxis = document.createElementNS("http://www.w3.org/2000/svg", "title");
titleAxis.textContent = "x-axis tooltip";
var gXtitle = document.getElementsByClassName("g-xtitle")[0];
gXtitle.insertBefore(titleAxis, gXtitle.childNodes[0]);
}, 500);
});'
shinyApp(
ui <- fluidPage(
tags$head(tags$script(HTML(jscode_testRect))),
tags$head(tags$script(HTML(jscode_xaxisPlotly))),
h4("<svg> rectangle - tooltip is functional"),
tags$div(HTML(testRect)),
h4("plotly heatmap - tooltip does not work"),
plotlyOutput("heatmap"),
br(),
br()
),
server = function(input, output){
output$heatmap <- renderPlotly(plot_ly() %>%
add_trace(data=dat, x=~x, y=~y, z=~z, type="heatmap") %>%
layout(
xaxis = list(title="foo"),
title = "Title"
)
)
}
)