r - 情节地悬停在点云背景中的图 block 上 - 如何显示工具提示?

标签 r ggplot2 r-plotly ggplotly

我正在将 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)上会像在低密度区域中一样迅速地显示工具提示。

编辑:添加了绘图的静态图像。

static version of the plot

最佳答案

您可以在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/

相关文章:

r - 将两个嵌套 tibble 变量相乘

r - 将数据框列提供给 xyplot 面板函数

r - 使用数据框列表将函数应用于列名称

r - Shiny 和 ggplot2 - 教程

python - 尝试在 python 中将 Plotly 图保存到图像文件时出现奇怪的错误?

r - 计算一个单词是否同时匹配两列

r - 从 geom_point 和 scale_fill_gradient 向图例添加一个点

r - 将两个 ggplot 与相同的 X 向量组合在一起是否是不好的做法/风格?

r - 情节(r): Unable to apply correct colors to 3D scatter and show legend at the same time

r - 颜色数 = 类别数的 plotly 条形图