我正在尝试访问customdata
通过javascrit分配给每个数据点(例如为每个点分配一个超链接)。然而,我注意到数据格式从一个图变为另一个图,这看起来很奇怪。
这在本例中完美运行(基于this https://stackoverflow.com/questions/71549382/how-to-make-tiles-open-a-hyperlink-using-ggplotly-r帖子),那就是当fill
审美是一种character
vector:
library(plotly)
library(htmlwidgets)
js <- "function(el, x) {
el.on('plotly_click', function(d) {
console.log(d);
console.log(d.points[0].data.customdata[0]);
});
}"
X <- data.frame(x = c(1, 2, 1, 2), y = c(1, 1, 2, 2), z = as.character(1:4), mydata = letters[1:4])
gg <- ggplot(X, aes(x = x, y = y, customdata = mydata)) + geom_tile(aes(fill = z))
ggplotly(gg) %>% onRender(js)
As can be seen, a single and correct custom data shows up when clicking on each point. The structure of the customdata is similar to other plots.
然而,当z
作为数字变量输入,自定义数据的结构表现得很奇怪:
X <- data.frame(x = c(1, 2, 1, 2), y = c(1, 1, 2, 2), z = 1:4, mydata = letters[1:4])
gg <- ggplot(X, aes(x = x, y = y, customdata = mydata)) + geom_tile(aes(fill = z))
ggplotly(gg) %>% onRender(js)
Is this a bug? How can I fix this? In fact, my dataset is much larger than the one in this example.
Edit
@ismirsehregal 提供了适用于上述示例的解决方案。然而,似乎customdata
获取向量数据as is,这似乎是非常错误的。因此,如果我们改变顺序X
the js
脚本停止工作。
展示:
library(plotly)
library(htmlwidgets)
js <- "function(el, x) {
el.on('plotly_click', function(d) {
var zdimensions = [ 0, 0 ];
var vecindex = 0;
var clickedcustomdata = '';
var zdimensions = [ d.points[0].data.z.length, d.points[0].data.z[0].length ];
vecindex = d.points[0].pointIndex[0]*zdimensions[1] + d.points[0].pointIndex[1];
clickedcustomdata = d.points[0].data.customdata[vecindex];
console.log(d);
console.log(clickedcustomdata);
});
}"
X <- data.frame(x = c(1, 2, 3, 1, 2, 3),
y = c(1, 1, 1, 2, 2, 2),
z = 1:6,
mydata = letters[1:6])
X <- X[order(-X$z),]
gg <- ggplot(X, aes(x = x, y = y, customdata = mydata)) + geom_tile(aes(fill = z))
fig <- ggplotly(gg) %>% onRender(js)
fig
我想一个潜在的解决方案是提前订购X
在 R 中所以它与矩阵顺序匹配?