在点云背景中的图块上徘徊-如何显示工具提示?

时间:2019-05-30 15:15:38

标签: r ggplot2 r-plotly ggplotly

我正在将ggplot2图转换为plotly。 该图由一个图块层(在背景中)和一个点层(在前景中)组成。 将鼠标悬停在图块上时,我希望有一些工具提示。

下面的代码通常可以为我提供所需的信息。当我将鼠标悬停在“无点”区域中的图块上时,将显示所需的工具提示。但是,当我将鼠标悬停在点密度高的区域时,工具提示不会出现。

我认为在layerData调用中使用ggplotly参数可能会有所帮助,但事实并非如此。

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

1 个答案:

答案 0 :(得分:2)

您可以在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!
相关问题