user1165199
user1165199

Reputation: 6649

Add markers at specific points in plotly line graph

I am plotting a plotly line graph, and want to highlight specific points on the line graph using markers (where another column in dataframe is not NA). Furthermore, when I hover over the plot I only want to see the y value when I am on the marker points, not the rest of the plot.

Here is a reproducible example and where I ave got so far in trying to do this:

library(plotly)
library(dplyr)

data <- data.frame(x = c(1:100), 
               random_y = rnorm(100, mean = 0),
               variable = sample(c('a', 'b', 'c'), 100, replace = TRUE),
               point = sample(c(1, rep(NA, 4)),100, replace = TRUE))

p <- plot_ly(data, x = ~x, y = ~random_y, type = 'scatter', mode = 'lines', color = ~variable, hoverinfo = 'none') %>% 
add_trace(data = filter(data, !is.na(point)), color = ~variable, mode = 'markers',
          x = ~x, y = ~random_y, hoverinfo = 'y')

This produces what I am after, but the issue is in the legend. It shows the legend for both the line and the marker plot.

I could put showlegend = F for one of the plots but then the issue is that when I click on the variable in the legend it doesn't isolate the traces properly. i.e. If I click the legend a I would want both the line graph and marker for a to show

Upvotes: 4

Views: 9444

Answers (1)

Maximilian Peters
Maximilian Peters

Reputation: 31709

You could use a loop to add the filter the dataframe for your your variables and add a trace for the line and another one for the markers. Both traces are grouped via legendgroup

enter image description here

library(plotly)
library(dplyr)

data <- data.frame(x = c(1:100), 
                   random_y = rnorm(100, mean = 0),
                   variable = sample(c('a', 'b', 'c'), 100, replace = TRUE),
                   point = sample(c(1, rep(NA, 4)),100, replace = TRUE))

p <- plot_ly(type = 'scatter', mode = 'lines')
for (i in levels(data$variable)) {
  print(i)
  p <- add_trace(p,
                 data = data[data$variable == i,],
                 legendgroup = i,
                 x = ~x, 
                 y = ~random_y, 
                 type = 'scatter', 
                 mode = 'lines', 
                 color = ~variable, 
                 hoverinfo = 'none'
  )
  p <- add_trace(p, 
                 data = data[(data$variable == i) & (!is.na(data$point)),],
                 legendgroup = i,
                 showlegend = F,
                 color = ~variable, 
                 mode = 'markers',
                 x = ~x, 
                 y = ~random_y, 
                 hoverinfo = 'y')
}

p

Upvotes: 6

Related Questions