I am working with a ggplot2
plot that passes to plotly and then outputs to html
using Rmarkdown. I am attempting to implement a JS function that opens the underlying URL when clicking on the points. Despite my efforts, the faceting seems to alter the point order and the existing solutions are not effective.
There is a related question on Stack Overflow (Add onclick open hyperlink event to an html widget created in R) that addresses a similar issue, but the solutions do not work due to the faceting issue. I also explored another post (Open hyperlink on click on an ggplot/plotly chart), but the suggested solution did not solve my problem.
Here is an example dataset:
library(ggplot2)
library(plotly)
library(htmlwidgets)
library(htmltools)
myData <- data.frame(x=c(1,2,3, 4, 6), y=c(3,2,1, 5, 4), type = c("a", "b", "c", "a", "b"), urls=c("https://www.google.com/", "http://stackoverflow.com/", "https://www.r-project.org/", "https://www.reddit.com/", "https://www.yahoo.com/"))
ggp <- ggplot(data=myData, aes(x=x, y=y)) +
geom_point() +
facet_wrap(type ~ .)
ply <- plotly_build(ggp)
ply$elementId <- "PlotlyGraph"
javascript <- HTML(paste("var myPlot = document.getElementById('PlotlyGraph');
myPlot.on('plotly_click', function(data){
var urls = ", toJSON(split(myData, myData$type)), ";
window.open(urls[data.points[0].data.name][data.points[0].pointNumber]['urls'],'_blank')
});", sep=''))
ply <- prependContent(ply, onStaticRenderComplete(javascript))
ply
The issue may be attributed to ggplot
not ordering the data as expected by JS. I am unsure how to resolve this. Any suggestions?