Search code examples
rggplot2r-plotlyggplotly

Hiding plotly tooltip color traces


Is there anyway to hide the tooltip color traces on a ggplot chart which has been made interactive w/ plotly? In the example below I would like my tooltip to go from this:

enter image description here

To this:

enter image description here

library(plotly)
library(tidyverse)

## fake data
dat <- data.frame(date = seq(as.Date("1910/1/1"), as.Date("1910/1/10"), "days"),
                  pred = 1:10,
                  pred2 = 31:40,
                  ci_low = seq(0, 9, 1),
                  ci_upper = seq(2, 11, 1))

## plot
p1 <- dat %>% 
  ggplot(aes(x = date, y = pred)) +
  geom_line(color = "red", aes(group = 1, text = paste("date:", date, "\npred:", pred, "\npred2:", pred2, "\nci_low:",  ci_low, "\nci_upper:", ci_upper))) +
  geom_line(aes(group = 1, x = date, y = pred2), color = "green") +
  geom_ribbon(aes(group = 1, x = date, ymin = ci_low, ymax = ci_upper), alpha = 0.2, linetype = 0)

## plotly-fy
ggplotly(p1, tooltip = c("text")) %>%
  layout(hovermode = "x unified") %>%
  style(hoverinfo = "skip", traces = 2)

Solution

  • Hopefully there is a better way but here is a workaround using a hidden trace:

    library(plotly)
    # library(tidyverse)
    
    ## fake data
    dat <- data.frame(date = seq(as.Date("1910/1/1"), as.Date("1910/1/10"), "days"),
                      pred = 1:10,
                      pred2 = 31:40,
                      ci_low = seq(0, 9, 1),
                      ci_upper = seq(2, 11, 1))
    
    ## plot
    p1 <- dat %>% 
      ggplot(aes(x = date, y = pred)) +
      geom_point(color = NA, aes(group = 1, text = paste("date:", date, "\npred:", pred, "\npred2:", pred2, "\nci_low:",  ci_low, "\nci_upper:", ci_upper))) +
      geom_line(aes(group = 1, x = date, y = pred), color = "red") +
      geom_line(aes(group = 1, x = date, y = pred2), color = "green") +
      geom_ribbon(aes(group = 1, x = date, ymin = ci_low, ymax = ci_upper), alpha = 0.2, linetype = 0)
    
    ## plotly-fy
    ggplotly(p1, tooltip = c("text")) %>%
      layout(hovermode = "x unified") %>%
      style(hoverinfo = "skip", traces = c(2:4))
    

    result