我试图通过javascrit访问分配给每个数据点的customdata(例如, for each 点分配一个超链接).然而,我注意到数据格式从一个图变为另一个图,这似乎很奇怪.

在本例中(基于this篇文章),这非常有效,即fill美学是character向量:

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)

enter image description here 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作为数字变量时,customdata的 struct 表现得很奇怪:

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)

enter image description here Is this a bug? How can I fix this? In fact, my dataset is much larger than the one in this example.

推荐答案

这是一个基于pointIndex的解决方案.

我根据提供的pointIndex计算customdata的向量指数:

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(clickedcustomdata);
         });
       }"

X <- data.frame(x = c(1, 2, 1, 2, 1, 2), y = c(1, 1, 2, 2, 3, 3), z = 1:6, mydata = letters[1:6])
gg <- ggplot(X, aes(x = x, y = y, customdata = mydata)) + geom_tile(aes(fill = z))
fig <- ggplotly(gg) %>% onRender(js)
fig

result

This美元是很有用的.

尽管如此,我还是鼓励您在GitHub上提交一个问题,因此这是正式修复的.

R相关问答推荐

R根据名称的载体对收件箱列采取行动

跨列应用多个摘要函数:summerise_all:列表对象无法强制为double类型'

从gtsummary包中使用tBL_strata()和tBL_summary()时删除变量标签

如何使用`ggplot2::geom_segment()`或`ggspatial::geom_spatial_segment()`来处理不在格林威治中心的sf对象?

基于不同组的列的相关性

如何使用按钮切换轨迹?

根据多个条件增加y轴高度以适应geom_text标签

R-更新面内部的栅格值

提取一个列表中单个列的重复观察结果R

如何使用tryCatch执行语句并忽略警告?

如何用书面利率绘制geom_bar图

计算两列中满足特定条件连续行之间的平均值

仅在R中的数据集开始和结束时删除所有 Select 列的具有NA的行

有没有可能用shiny 的书签恢复手风琴面板?

R中时间间隔的大向量与参考时间间隔的相交

Rmarkdown::Render vs Source()

如何为混合模型输出绘制不同的线型?

如何显示准确的p值而不是<;0.001*?

如何在AER::ivreg中指定仪器?

我正在try 创建一个接近cos(X)的值的While循环,以便它在-或+1-E10范围内