【发布时间】:2018-09-17 13:32:56
【问题描述】:
这是针对Add onclick open hyperlink event to an html widget created in R 提供的答案的后续问题。考虑以下示例:
library(ggplot2)
library(plotly)
library(htmlwidgets)
library(htmltools)
myData <- data.frame(
x=c(1,2,3),
y=c(3,2,1),
label=c("Google", "Bing", "R"),
category=c("search", "search", "other"),
urls=c("http://google.de", "http://bing.com", "http://r-project.org")
)
f <- function(p) {
ply <- ggplotly(p)
javascript <- HTML(paste("
var myPlot = document.getElementById('", ply$elementId, "');
myPlot.on('plotly_click', function(data){
var urls = ['", paste(myData$urls, collapse = "', '"), "'];
window.open(urls[data.points[0].pointNumber],'_blank');
});", sep=''))
prependContent(ply, onStaticRenderComplete(javascript))
}
这按预期工作 - 单击任何点都会打开相应的 url:
f(ggplot(myData, aes(x=x, y=y)) + geom_point(aes(text=label)))
这不能按预期工作 - 索引不再匹配:
f(ggplot(myData, aes(x=x, y=y)) + geom_point(aes(text=label, color=category)))
情节对象不同,似乎pointNumber 不再保存所有点的绝对索引,而是(颜色)分组中的索引。
关于如何调整示例使其适用于一般用例以及颜色/填充分组的任何想法?
【问题讨论】:
标签: r ggplot2 plotly htmlwidgets