data visualization – R ggplotly with hovermode = “x unified”

I managed to get this ggplotly graphic:

enter image description here

It uses the layout option hovermode = "x unified" (see https://plotly.com/r/hover-text-and-formatting/).

To get the value of Time (x) in the tooltip, I had to add this transparent geom_line in my code:

  geom_line(aes(
    y = NA, 
    text = paste0(
      "Time: ", Time
    ),
  ), alpha = 0) + 

Here is the full code:

library(plotly)

dat <- data.frame(
  Time = 1:10,
  Average = rnorm(10),
  Std = rgamma(10, 10, 10)
)
dat <- transform(dat, Ymin = Average - Std)
dat <- transform(dat, Ymax = Average + Std)

gg <- ggplot(
  dat, 
  aes(
    x = Time, 
    group = 1
  )
) + 
  geom_line(aes(
    y = NA, 
    text = paste0(
      "Time: ", Time
    ),
  ), alpha = 0) + 
  geom_line(aes(
    y = Average, 
    linetype = "Average", 
    colour = "Average",
    text = paste0(
      "Average: ", Average
    )
  )) + 
  geom_line(aes(
    y = Ymin, 
    linetype = "Ymin", 
    colour = "Ymin",
    text = paste0(
      "Ymin: ", Ymin
    )
  )) + 
  geom_line(aes(
    y = Ymax, 
    linetype = "Ymax", 
    colour = "Ymax",
    text = paste0(
      "Ymax: ", Ymax
    )
  )) +
  scale_linetype_manual(
    values = c(Ymin = "dashed", Average = "solid", Ymax = "dashed")
  ) +
  scale_colour_manual(
    values = c(Ymin = "green", Average = "red", Ymax = "green")
  ) + 
  guides(
    colour = guide_legend(title = ""), 
    linetype = guide_legend(title = "")
  )

ggplotly(gg, tooltip = "text") %>%
  layout(hovermode = "x unified")

Do you have a simpler solution?