Search code examples
rplotlyr-plotly

How to define separate color palettes per trace in R plotly plots?


I want to define two vectors of colors and apply them to two plotly traces.

col2 <- c("#b72b7f", "#2ba5b7", "#3e8236", "#f87b60", "#000000")
col1 <- c("#e65353", "#62e653", "#53a4e6", "#53e6da", "#e6b053")

iris %>%
  plot_ly() %>%
  add_trace(x = ~Sepal.Length, y = 0.3, color = ~Species, colors = col1) %>%
  add_trace(x = ~Sepal.Width, y = 0.6, color = ~Species, colors = col2)

However, it seems that plotly use only the colors in col1 to color both of the traces. What can I do to achieve the desired result?

Image showing two lines of dots. They both use the same groups of colors.


Solution

  • As both traces share the same legend, looks like it will be necessary to make two distinct groups to have two colors groups :

    library(dplyr)
    library(plotly)
    
    col1 <- c("#b72b7f", "#2ba5b7", "#3e8236", "#f87b60", "#000000")
    col2 <- c("#e65353", "#62e653", "#53a4e6", "#53e6da", "#e6b053")
    
    col1 <- col1[1:length(unique(iris$Species))]
    col2 <- col2[1:length(unique(iris$Species))]
    
    col <- c(col1,col2)
    
    iris %>%
      plot_ly() %>%
      add_trace(x = ~Sepal.Length, y = 0.3, color = ~paste("1 -", Species), colors = col) %>%
      add_trace(x = ~Sepal.Width, y = 0.6, color = ~paste("2 -", Species), colors = col)
    

    enter image description here