Search code examples
rggplot2plotlyr-plotly

Show tooltip on plotly based on x-axis


I have an interactive chart which shows a predicted value and an upper and lower confidence interval. I have the chart looking exactly as I want it to, however the tooltip behavior is not what is desired. Is there anyway to show tooltip information based on where on the x-axis the cursor is, rather than over what specific part of the line or confidence interval you are at?

## libraries
library(tidyverse)
library(plotly)

## fake data
dat <- data.frame(date = seq(as.Date("1910/1/1"), as.Date("1910/1/10"), "days"),
                  pred = 1:10,
                  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") +
  geom_ribbon(aes(x = date, ymin = ci_low, ymax = ci_upper), alpha = 0.2, linetype = 0)

## plotly-fy
ggplotly(p1)

For example, if the cursor is at the intersection of January 08 and 3, I would like the tooltip to show the predicted value and the upper and lower confidence interval, all of which are contained above that point. Additionally, if I am scrolling over the line, I would like the confidence intervals shown as well, as shown below. Basically I just want a standard tooltip that shows the same information based exclusively on where on the x-axis the user is, regardless of the y-axis.

enter image description here


Solution

  • You can set the hovermode to "x unified":

    ## libraries
    # library(tidyverse)
    library(plotly)
    
    ## fake data
    dat <- data.frame(date = seq(as.Date("1910/1/1"), as.Date("1910/1/10"), "days"),
                      pred = 1:10,
                      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, "\nci_low:", ci_low, "\nci_upper:", ci_upper))) +
      geom_ribbon(aes(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)
    

    result

    Edit: To control the displayed hoverinfo we can use ggplotly's tooltip argument along with a custom "text" aesthetic. The hoverinfo of the geom_ribbon-trace can be hidden via style().

    In the plotly book you can find some great examples regarding this.