Weiwen Gu
Weiwen Gu

Reputation: 215

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

Plotly has the feature of showing hover text of multiple lines simultaneously. For example:

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

However, if their modes are different, the hover text won't be grouped. For example:

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 has a way to do it (Line Plot Modes) I couldn't find the solution to plotly in R.

Thanks

Upvotes: 2

Views: 1588

Answers (1)

Maximilian Peters
Maximilian Peters

Reputation: 31739

If you look at the raw JSON of the example provided in the link you can see that hovermode is set to x (the default is all).

If you set hovermode to x in layout in R you should get the desired output as well.

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

enter image description here

Upvotes: 5

Related Questions