在 plotly R 中以不同模式对多行悬停文本进行分组

Grouping hover text of multiple line with different mode in plotly R

Plotly 具有同时显示多行悬停文本的功能。例如:

dt <- data.table(x = 1:10, y = rnorm(10), z = rnorm(10)+2)
plot_ly(type = "scatter", mode = "lines") %>% 
    add_trace(x = dt$x, y = dt$y, name = "curve 1", mode = "lines") %>% 
    add_trace(y = dt$z, name = "curve 2", mode = "lines")

但是,如果它们的模式不同,悬停文本将不会被分组。例如:

dt <- data.table(x = 1:10, y = rnorm(10), z = rnorm(10)+2) 
plot_ly(type = "scatter", mode = "lines") %>%
    add_trace(x = dt$x, y = dt$y, name = "curve 1", mode = "lines+markers") %>% 
    add_trace(y = dt$z, name = "curve 2", mode = "lines")

plotly in python 有办法做到这一点 (Line Plot Modes) 我在 R 中找不到 plotly 的解决方案。

谢谢

如果您查看 link 中提供的示例的原始 JSON,您可以看到 hovermode 设置为 x(默认值为 all).

如果您在 layoutR 中将 hovermode 设置为 x,您也应该得到所需的输出。

library(data.table)
library(plotly)

set.seed(42)

dt <- data.table(x = 1:10, y = rnorm(10), z = rnorm(10)+2) 
plot_ly(type = "scatter", mode = "lines") %>% 
  add_trace(y = dt$y, name = "curve 1", mode = "lines+markers") %>% 
  add_trace(y = dt$z, name = "curve 2", mode = "lines") %>% 
  layout(hovermode = 'x')