Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'd like to make my scatterplot points clickable and have each point's respective hyperlink open when clicked. I am trying to do this using ggplotly. There is a simple way to do this when building the plot using plotly()(see first example below). However, when running it on ggplotly, an empty webpage opens when I click.

Anyone know how I can make this work with the code below? Could there be a solution on the OnRender portion of the code (not familiar with javascript)? The first code chunk using plotly works. The second code chunk is my basic attempt at thisusing ggplotly, which does not work.

Any guidance on this would be amazing! thanks in advance

library(plotly)
library(htmlwidgets)
library(dplyr)

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

#1. Using plotly
p <- plot_ly(mtcars, x = ~wt, y = ~mpg) %>%
  add_markers(customdata = ~url)
onRender(p, "
         function(el, x) {
         el.on('plotly_click', function(d) {
         var url = d.points[0].customdata;
         window.open(url);
         });
         }
         ")

#2. Using ggplotly`
p <- ggplot(data = mtcars, aes(x = wt, y = mpg))+
  geom_point()
pp <- ggplotly(p)
pp  <- add_markers(pp, customdata = ~url)
onRender(pp, "
         function(el, x) {
         el.on('plotly_click', function(d) {
         var url = d.points[0].customdata;
         url
         window.open(url);
         });
         }
         ")
like image 320
Margo Avatar asked Aug 03 '18 23:08

Margo


2 Answers

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);
         });
         }
         ")
like image 88
Stéphane Laurent Avatar answered Oct 31 '22 10:10

Stéphane Laurent


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);
     });
     }
     ")
like image 37
fc9.30 Avatar answered Oct 31 '22 10:10

fc9.30