Home > Software design >  Hover over images with plotly in R
Hover over images with plotly in R

Time:06-17

I'm looking to display information when I hover over a logo plot created with ggplot, something similar to : Flag plot The images are stored locally on my computer. The problem is that neither annotations_custom, nor annotation_raster, nor ggdraw, etc. is yet implemented for Plotly.

I tried to create the graph directly with Plotly, but it seems that it's not possible to read stored images directly without going through a Shiny app (Is there a way to read images stored locally into Plotly?).

The only solution seems to be to use JavaScript, so I'm trying to adapt the following code found here: https://anchormen.nl/blog/data-science-ai/images-in-plotly-with-r/

library(tidyverse)
library(plotly)

g <- ggplot(iris, aes(x = Sepal.Length,
y = Petal.Length,
color = Species,
text = Species))   geom_point()
p <- ggplotly(g, tooltip = "text")

p %>% htmlwidgets::onRender("
function(el, x) {
// when hovering over an element, do something
el.on('plotly_hover', function(d) {
// extract tooltip text
txt = d.points[0].data.text;
// image is stored locally
image_location = '1.png';
// define image to be shown
var img = {
// location of image
source: image_location,
// top-left corner
x: 0,
y: 1,
sizex: 0.2,
sizey: 0.2,
xref: 'paper',
yref: 'paper'
};
// show image and annotation
Plotly.relayout(el.id, {
images: [img]
});
})
}
")
  1. By reusing the code as is, I manage to display an online image, but not a locally stored image, whether using a relative path (the working directory is set to source file location) or absolute, starting with file:///C:/Users/. The graph is displayed and I can hover over the points, but the image is not displayed on hover.

  2. If it is ever possible to display locally stored images, I would greatly appreciate some help in adapting the code so that the image does not display at the top left but over the dots to recreate a logo plot.

Thanks a lot!

CodePudding user response:

Solved with this: https://plotly-r.com/embedding-images.html. It finally seems to be easier than expected to use locally stored images.

  • Related