Add markers at specific points in a graphic plot

I am drawing a graphical line graph and want to highlight specific points on the line graph using markers (where the other column in the dataframe is not NA). Also, when I am 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's a reproducible example and where I've tried so far:

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 creates what I need, but the problem is in the legend. It shows the legend for both the line and the marker plot.

I could put in showlegend = F

for one of the plots, but then the problem is that when I click on a variable in the legend, it does not isolate the traces properly. those. if i click on legend a

i would like both line graph and marker to a

display

+3


source to share


1 answer


You can use a loop to add a filter for your variables data and add a trace for the string and another for the markers. Both tracks are grouped throughlegendgroup

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

      

+2


source







All Articles