一种方法是
- 通过添加 Javascript 代码
onStaticRenderComplete
为了在绘图渲染后执行它
- Javascript 事件是对示例的简单修改here
- 该 URL 通过以下方式打开window.open
对于具有不同轨迹的通用解决方案,请参阅:单击 ggplot/plotly 图表打开超链接
完整代码
library(ggplot2)
library(plotly)
library(htmlwidgets)
library(htmltools)
path.test.results <- "C:\\Users\\img\\"
myData <- data.frame(x=c(1,2,3), y=c(3,2,1), urls=c("https://www.google.com/", "http://stackoverflow.com/", "https://www.r-project.org/"))
myLinks <- c("https://www.google.com/", "http://stackoverflow.com/", "https://www.r-project.org/")
ggp <- ggplot(data=myData, aes(x=x, y=y)) + geom_point()
ply <- plotly_build(ggp)
ply$elementId <- "PlotlyGraph"
html <- HTML(paste(
paste('<button type="button" onclick="document.getElementById(',"'", 'PlotlyGraph', "'", ').style.display=',
"'", 'none', "'", '">Hide Plot</button>', sep=''),
paste('<button type="button" onclick="document.getElementById(',"'", 'PlotlyGraph', "'", ').style.display=',
"'", 'block', "'", '">Show Plot</button>', sep='')
,sep=''))
javascript <- HTML(paste("var myPlot = document.getElementById('PlotlyGraph');
myPlot.on('plotly_click', function(data){
var urls = ['", paste(myLinks, collapse = "', '"), "'];
window.open(urls[data.points[0].pointNumber],'_blank');
});", sep=''))
ply <- prependContent(ply, html)
ply <- prependContent(ply, onStaticRenderComplete(javascript))
saveWidget(widget=ply, file=paste(path.test.results, "test.html", sep=""), selfcontained = FALSE)