Home > Net >  How to make tiles open a hyperlink using ggplotly - R
How to make tiles open a hyperlink using ggplotly - R

Time:03-23

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.

CodePudding user response:

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
  • Related