Search code examples
rggplot2plotlyr-plotly

How to manually assign linetype to lines in plotly


I have a plot like this:

library(plotly)
library(tidyr)
library(dplyr)

data.frame(date = seq(ymd('2020-01-01'), ymd('2020-05-31'), by = '1 day'), 
           sin = sin(seq(-pi, pi, length.out = 152)), 
           cos = cos(seq(-pi, pi, length.out = 152))) %>% 
  gather(k, v, -date) %>% 
  plot_ly() %>% 
  add_lines(x = ~date, y = ~v, linetype = ~k, color = I('black'))

The output looks like below:

enter image description here

What I'd like to do is to manually assign linetype to values of k variable, and for example, assign dashed line to cos and solid line to sin no matter of their order. Basically I'm looking for equivalent for ggplot2::scale_linetype_manual in plotly? How can I achieve this without adding new trace for each line? (I don't know the exact number of k values beforehand)


Solution

  • Similar to this can be achieved by using a named vector of linetypes like so:

    library(plotly)
    library(tidyr)
    library(dplyr)
    library(lubridate)
    
    lty <- c(cos = "dash", sin = "solid")
    
    data.frame(date = seq(ymd('2020-01-01'), ymd('2020-05-31'), by = '1 day'), 
               sin = sin(seq(-pi, pi, length.out = 152)), 
               cos = cos(seq(-pi, pi, length.out = 152))) %>% 
      gather(k, v, -date) %>% 
      plot_ly() %>% 
      add_lines(x = ~date, y = ~v, linetype = ~k, color = I('black'), linetypes = lty)
    

    enter image description here