Luc
Luc

Reputation: 958

R plotly add legend from other data frame

I cannot get this to work...I want to show the legend of the 'highlight' dataframe (Type A/B/C with col and pch).

The graph I have is one that combines data from 2 data frames:

data <- data.frame(x=1:100, y=cumsum(runif(n = 100, min = -20 ,max = 30)))

highlight <- data[sample(1:100, 15, replace = F),]
highlight$TextToDisplay <- sample(c("Type A", "Type B", "Type C"), 15, replace=TRUE)
highlight$col[highlight$TextToDisplay == "Type A"] <- "#FF0000"
highlight$col[highlight$TextToDisplay == "Type B"] <- "#00FF00"
highlight$col[highlight$TextToDisplay == "Type C"] <- "#FFFF00"
highlight$pch[highlight$TextToDisplay == "Type A"] <- 2
highlight$pch[highlight$TextToDisplay == "Type B"] <- 4
highlight$pch[highlight$TextToDisplay == "Type C"] <- 7


fig <- plot_ly(data, 
               x= ~x, 
               y = ~y, 
               type = 'scatter', 
               mode = 'lines', 
               showlegend=FALSE) %>% 
  add_trace( x    =  highlight$x,
             y    =  highlight$y,
             col  = ~highlight$col,
             pch  = ~highlight$pch,
             mode = "markers",
             marker = list(color   = highlight$col, 
                           symbol  = highlight$pch, 
                           size    = 12),
             showlegend = TRUE
  ) %>% 
  layout(legend = list(x = 5, y = 5))
fig

Upvotes: 1

Views: 263

Answers (1)

stefan
stefan

Reputation: 125607

Instead of adding colors and symbols to your data simply use named vectors for colors and symbols. These vectors can be passed as arguments to plot_ly(). In add_trace map TextToDisplay on color and symbol (BTW: There are no col or pch attrributes in plotly) and plotly will pick the right color and symbol automatically and will give you a nice legend. Try this:

set.seed(42)

data <- data.frame(x=1:100, y=cumsum(runif(n = 100, min = -20 ,max = 30)))

highlight <- data[sample(1:100, 15, replace = F),]
highlight$TextToDisplay <- sample(c("Type A", "Type B", "Type C"), 15, replace=TRUE)

library(plotly)

fig <- plot_ly(data, 
               x= ~x, 
               y = ~y, 
               type = 'scatter', 
               mode = 'lines',
               colors = c("Type A" = "#FF0000", "Type B" = "#00FF00", "Type C" = "#FFFF00"),
               symbols = c("Type A" = 2, "Type B" = 4, "Type C" = 7),
               showlegend=FALSE) %>% 
  add_trace(data = highlight, 
            x    =  ~x,
            y    =  ~y,
            color  = ~TextToDisplay,
            symbol  = ~TextToDisplay,
            mode = "markers",
            marker = list(size    = 12),
            showlegend = TRUE
  ) %>% 
  layout(legend = list(x = 5, y = 5))
fig

enter image description here

Upvotes: 2

Related Questions