我正在将 ggplot2 图转换为plotly。 该图由图 block 层(在背景中)和点层(在前景中)组成。 我希望将鼠标悬停在图 block 上时有工具提示。
下面的代码大部分都能满足我的需求。当我将鼠标悬停在“无点”区域中的图 block 上时,会出现所需的工具提示。但是,当我将鼠标悬停在点密度较高的区域时,工具提示不会出现。
我认为在 ggplotly
调用中使用 layerData
参数可能会有所帮助,但事实并非如此。
library(ggplot2)
library(dplyr)
library(plotly)
set.seed(1)
dat_points <- data.frame(x = rnorm(100), y = rnorm(100))
dat_tiles <- expand.grid(tx = -3:3, ty = -3:3)
dat_tiles$val <- rnorm(nrow(dat_tiles))
dat_tiles$label <- sample(LETTERS[1:5], nrow(dat_tiles), replace = T)
p <- ggplot() +
geom_tile(data = dat_tiles, aes(x = tx, y = ty, fill = val, text = label)) +
geom_point(data = dat_points, aes(x = x, y = y), alpha = .5)
gg <- ggplotly(p, tooltip = "text")
gg
我希望将鼠标悬停在高密度区域(例如 0、0)上会像在低密度区域中一样迅速地显示工具提示。
编辑:添加了绘图的静态图像。
最佳答案
您可以在p
中切换图层的顺序,并且由于ggplotly()
如何从ggplot
对象构造,您会得到一个看起来相同的情节,但具有所需的工具提示行为!
p <- ggplot() +
geom_point(data = dat_points, aes(x = x, y = y), alpha = 1) +
geom_tile(data = dat_tiles, aes(x = tx, y = ty, fill = val, text = label))
p # this looks bad
gg <- ggplotly(p, tooltip = "text")
gg # but this looks good!
关于r - 情节地悬停在点云背景中的图 block 上 - 如何显示工具提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56381006/