I'm converting a ggplot2 plot to plotly. The plot consists of a tile layer (in the background) and a point layer (in the foreground). I would like to have tooltips when hovering on the tiles.
The code below mostly gets me what I am looking for. When I hover on tiles in "points free" zones, the desired tooltip appears. However, when I hover in areas with a high density of dots, the tooltips do not appear.
I thought that playing with the layerData
parameter in the ggplotly
call might help, but that was not the case.
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
I would like that hovering on high density areas (e.g. 0, 0) would bring up tooltips with the same promptness as in low density areas.
EDIT: added static image of the plot.
You can switch the order of you layers in p
and because of how ggplotly()
constructs from a ggplot
object, you get an identical looking plot, but with the desired tooltip behavior!
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!