Search code examples
rplotly

Legend Won't Appear for Plotly Trace


My plot won't show the symbol that I added using "add_markers". My hope was that the legend would appear to the right of the plot, but for some reason, it does not.

library(plotly)
library(tidyverse)

my_data = data.frame(
  Y_LABEL = c("Label1", "Label2"),
  START = c(66, 72),
  END = c(20, 28), 
  COLOR_VAR = c("Color1", "Color2"),
  SYMBOL_TIME = c(7.2, 7.2)
)


my_plot <- plot_ly() %>%
  add_segments(data=my_data, 
               x=~START, xend=~END, y=~Y_LABEL, yend=~Y_LABEL,
               color=~COLOR_VAR, line=list(width=9), showlegend=F)


my_plot = my_plot %>% add_markers(x = ~SYMBOL_TIME, y = "Symbol", 
                                  showlegend = T, inherit = F,
                                  marker=list(symbol = "diamond", 
                                              size = 9, 
                                              color = "white", 
                                              line = list(color = "blue", 
                                                          width = 1)),
                                  name = "My Symbol")

Solution

  • You could use the layout function to add the legend for the respective traces like this:

    library(plotly)
    library(tidyverse)
    
    my_plot <- plot_ly() %>%
      add_segments(data=my_data, 
                   x=~START, xend=~END, y=~Y_LABEL, yend=~Y_LABEL,
                   color=~COLOR_VAR, line=list(width=9), showlegend=F) %>%
      add_markers(x = ~SYMBOL_TIME, y = "Symbol", 
                  showlegend = T, inherit = T,
                  marker=list(symbol = "diamond", 
                              size = 9, 
                              color = "white", 
                              line = list(color = "blue", 
                                          width = 1)),
                  name = "My Symbol") %>%
      layout(showlegend = T)
    
    my_plot
    

    Created on 2023-01-28 with reprex v2.0.2