1
votes

I would like to add to the hover information about the difference between the values in the chart. It would be best if it looks like the graphics below.

enter image description here

My example:

library(plotly)
trace_1 <- sample(1:20)
main <- sample(1:20)
diff <-main - trace_1
x <- c(1:20)

data <- data.frame(x, trace_1, diff)

fig <- plot_ly(data, x = ~x, y = ~trace_1, name = 'trace 1', type = 'scatter', mode = 'lines') 
fig <- fig %>% add_trace(y = ~main, name = 'main', type = 'scatter', mode = 'lines') 
fig <- fig %>%
  layout(hovermode = "x unified")
fig

1
would it work adding another line with the "y" being the difference? and perhaps a transparent stroke?Paladinic

1 Answers

2
votes

You could add another line that is calculated as the difference andd set the line color to transparent.

library(plotly)

df = mtcars %>%
  tibble::rownames_to_column("cars") %>%
  mutate(diff = mpg - wt)

plot_ly(df) %>% 
  add_lines(x = ~cars,y = ~mpg,name="mpg") %>% 
  add_lines(x = ~cars,y = ~wt,name="weight") %>% 
  add_lines(x = ~cars,y = ~diff,name="diff",line = list(color = "rgba(0,0,0,0)")) 

enter image description here