How to make scatterplot points open a hyperlink using ggplotly - R

Solution 1:

Looks like add_markers(pp, customdata = ~url) has no effect. That works by doing:

p <- ggplot(data = mtcars, aes(x = wt, y = mpg)) + geom_point()
pp <- ggplotly(p)
pp$x$data[[1]]$customdata <- mtcars$url
#pp  <- add_markers(pp, customdata = ~url)
ppp <- onRender(pp, "
         function(el, x) {
         el.on('plotly_click', function(d) {
         var url = d.points[0].customdata;
         //url
         window.open(url);
         });
         }
         ")

Solution 2:

This is a more generic version of Stéphane's solution, which is not working when using groups, colors, facets etc. Everything is fine if you specify your urls directly in the customdata aesthetic:

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

p <- ggplot(data = mtcars, aes(x = wt, y = mpg, color = as.character(carb), customdata = url)) + 
geom_point() + 
facet_wrap(~cyl)
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);
     });
     }
     ")