2

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.

1 Answer 1

3
+50

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Waldi! This logic seem at least to apply to plots with two discrete color palettes. And, what if the second trace was trying to use continuous color (fx by mapping color to Petal.Length), instead of discrete? If you have any idea, i'd be grateful, thanks! :-)
@Bastian, glad I could help! For continous scale, if color arg values are positive you could use a color gradient specifying negative and positive values, and set trace 2 color values to negative

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.