1

I would like tiles generated from geom_tile() to open a hyperlink using ggplotly and htmlwidgets. There is already an answer for points on a scatter plot.

This is what I have so far:

mtcars$url <- paste0("http://google.com/search?q=", gsub(" ", "+", rownames(mtcars)))

p <- ggplot(data = mtcars, aes(x = wt, y = mpg, fill = as.character(carb), customdata = url)) + 
  geom_tile(width = .2, height = 1)
pp <- ggplotly(p)
ppp <- htmlwidgets::onRender(pp, "
     function(el, x) {
     el.on('plotly_click', function(d) {
     var url = d.points[0].customdata;
     //url
     window.open(url);
     });
     }
     ")

A new web browser tab does open, but it is blank.

mat
  • 2,412
  • 5
  • 31
  • 69

1 Answers1

1

It seems the structure was changed a little.

Please check the following:

library(plotly)

mtcars$url <- paste0("https://google.com/search?q=", gsub(" ", "+", rownames(mtcars)))

p <- ggplot(data = mtcars, aes(x = wt, y = mpg, fill = as.character(carb), customdata = url)) + 
  geom_tile(width = .2, height = 1)
pp <- ggplotly(p)

plotly_json(pp)

ppp <- htmlwidgets::onRender(pp, "
     function(el, x) {
     el.on('plotly_click', function(d) {
     // console.log(d);
     var url = d.points[0].data.customdata[0];
     window.open(url);
     });
     }
     ")
ppp
ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
  • Perfect! Mind explaining how you find out the solution? Via the web browser console? – mat Mar 22 '22 at 09:57
  • 1
    @mat exactly - I left the `console.log(d);` in there for inspection of the data you receive on click. – ismirsehregal Mar 22 '22 at 10:04
  • This solution does not work anymore when using a numeric variable as the `fill` aesthetic. See: https://stackoverflow.com/questions/71739062/r-plotly-customdata-format-variations – mat Apr 04 '22 at 14:35