I want to embed html code inside the plotly's on hover tooltip. Here is a working example:
plotly::plot_ly(
type = "pie",
labels = "A",
hovertext = '<i>text in italics</i>', # Renders text in italics
hoverinfo = "text"
)
This reprex seems to work perfectly fine, by rendering the text in italics. However, more complex html code seems to fail to be rendered as html, and is instead rendered as plain text. In my case, what I want is to embed an image inside the tooltip, like the following:
plotly::plot_ly(
type = "pie",
labels = "A",
hovertext = '<img src="https://cran.r-project.org/Rlogo.svg">', # Does not render as html
hoverinfo = "text"
)
A few other values I have tried to use for hovertext
(or for text
, for this matter both work the same):
Values that are rendered just as plain text:
'<div><i>text in italics</i></div>'
'<div><img src="https://cran.r-project.org/Rlogo.svg"></div>',
'<img src="https://cran.r-project.org/Rlogo.svg">',
htmltools::HTML('<img src="https://cran.r-project.org/Rlogo.svg">'),
htmltools::HTML('<div><img src="https://cran.r-project.org/Rlogo.svg"></div>'),
To be sure, the first one renders as "<div>text in italics</div>" (italics ok)
Values that make the tooltip not to work at all:
htmltools::img(src="https://cran.r-project.org/Rlogo.svg")
htmltools::div(htmltools::img(src="https://cran.r-project.org/Rlogo.svg"))
htmltools::div('<img src="https://cran.r-project.org/Rlogo.svg">')
Related posts and likely solutions:
Hover Events with JavaScript in R could at least partially solve the problem (I could go with an image that changes instead of the tooltip showing up); however, this page seems to be outdated. Also, I don't get how the javascript code is embedded.
gdlmx solution here gives also some ideas that may be helpful. However, my code must generate a static html output, so I cannot rely on Shiny.
Bob's Your Uncle seems to find a solution for d3heatmap, which if I'm not wrong is built over D3 as plotly is. I'm not that familiar with javascript though, and I'm not sure I can follow his code very well, or whether his solution would apply to plotly tooltips as well.
As explained by Brandon Bertelsen here, DT::datatable
has a escape
parameter that can be set to FALSE
, to avoid escaping html code inside a datatable, thus rendering the html code inside the table properly. As far as I know, plotly doesn't have anything like that. Also, I think datatables is not built on top of D3 (but I'm not 100% sure).
Any ideas about how to solve this? Thanks so much!