Search code examples
rplotlyggplotly

selectize widget of ggplotly highlight not always visible (depends on order of geoms?)


I want to do an interactive scatterplot where I can

  • highlight individual points
  • a tooltip shows me the id
  • search for specific id with a selectize widget

enter image description here

I tried for some time with plotly and ended up with this code

library(tidyverse)
library(plotly)
set.seed(1)
dat <- tibble(id = LETTERS[1:10],
              trt = factor(rep(0:1, 5)),
              x = rnorm(10),
              y = x + rnorm(10, sd = 0.2)) %>% 
  highlight_key(~id)
dat %>% 
  {ggplot(., aes(x = x, y = y, group = id, color = trt)) +
      geom_point() +
      geom_hline(yintercept = 0, linetype = "dashed")} %>% 
  ggplotly(tooltip = c("id")) %>% 
  highlight(on = "plotly_hover", selectize = TRUE)

In a next step I wanted to plot the hline behind the points (i.e. reverse the order of the geoms)

However this led to problems shown below (widget missing or only working for one trt group

## no color, geom order reversed
## => selectize.js widget is completely missing
dat %>% 
  {ggplot(., aes(x = x, y = y, group = id)) +
      geom_hline(yintercept = 0, linetype = "dashed") +
      geom_point()} %>% 
  ggplotly(tooltip = c("id")) %>% 
  highlight(on = "plotly_hover", selectize = TRUE)

## color by trt, geom order reversed
## => selectize.js widget only works for data where trt = 0
dat %>% 
  {ggplot(., aes(x = x, y = y, group = id, color = trt)) +
      geom_hline(yintercept = 0, linetype = "dashed") +
      geom_point()} %>% 
  ggplotly(tooltip = c("id")) %>% 
  highlight(on = "plotly_hover", selectize = TRUE)

Can somebody explain this strange behavior? What if I would like to reverse the order of geoms i.e. hline ploted behind points?


Solution

  • The release of Plotly 4.10.2 solved the problem. The release notes mention some improvements of the selectize.js implementation.