Search code examples
rplotly

Color mapping not working with plotly in R


I have a data frame like this

df1 <- data.frame("time" = 1:10, A1 = rnorm(10), B1 = rnorm(10), C1 = rnorm(10), D1 = rnorm(10))
df2 <- data.frame("time" = 1:5, A2 = rnorm(5), B2 = rnorm(5),  C2 = rnorm(5), D2 = rnorm(5))

I want to plot df1 with "time" on x axis and all other variables on the y axis. Similarly, I want to plot df2 with "time" on x axis and all other variables on the y axis. In this case, I want the lines to be "dot" and markers to be hollow circles. I specified the following colors to be used

my_colors <- c(             ## add the standard plotly colors
  'red',  
  'blue',  
  'green',  
  'yellow'
) 

Here is the plotly code I tried

longDF1 <- melt(df1, id.vars = "time")
longDF2 <- melt(df2, id.vars = "time")
  
  plot_ly() %>%
  add_trace(data = longDF1, x = ~time, y = ~value, type = 'scatter', mode = 'lines+markers', color = ~variable,
            line = list(color = my_colors, dash = 'solid'),
            marker = list(color = my_colors, symbol = 'circle')) %>% 
  add_trace(data = longDF2, x = ~time, y = ~value, type = 'scatter', mode = 'lines+markers', color = ~variable,
            line = list(color = my_colors, dash = 'dot'),
            marker = list(color = my_colors, symbol = 'circle-open'))

The colors dont seem to be added to the plots. Instead, plotly generates its own colors. Any ideas how to solve this?


Solution

  • To get your desired colors drop the color attribute from the line and marker specs and instead pass your color vector to the colors attribute, where it is sufficient to pass it to the first trace only or directly inside plot_ly() as I do below. Additionally, as you you have eight different categories duplicate your color vector, i.e. use colors = c(my_colors, my_colors).

    library(plotly)
    
    set.seed(123)
    
    plot_ly(colors = c(my_colors, my_colors)) %>%
      add_trace(
        data = longDF1, x = ~time, y = ~value, type = "scatter", mode = "lines+markers", color = ~variable,
        line = list(dash = "solid"),
        marker = list(symbol = "circle")
      ) %>%
      add_trace(
        data = longDF2, x = ~time, y = ~value, type = "scatter", mode = "lines+markers", color = ~variable,
        line = list(dash = "dot"),
        marker = list(symbol = "circle-open")
      )