在 r-plotly 中显示值之间的差异

Show difference between values in r-plotly

我想在悬停信息中添加有关图表中值之间差异的信息。如果像下图这样就最好了

我的例子:

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

您可以添加另一条计算为差异的线并将线颜色设置为透明。

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)"))