When I'm trying to define a custom palette, say of blue and red colors, I get magenta instead of blue. Let's consider an example taken from plotly documentation:
library(plotly)
pal <- c("red", "blue", "green")
p <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length,
color = ~Species, colors = pal)
p
This works as expected. Each of three species get it's own color: red, blue or green.
Then I prepare a new data set, removing "virginica", and plotting the result:
library(dplyr)
pal <- c("red", "blue", "green")
iris_new<- filter(iris, Species == "setosa" | Species == "versicolor")
p <- plot_ly(data = iris_new, x = ~Sepal.Length, y = ~Petal.Length,
color = ~Species, colors = pal)
p
Now "setosa" is red and "versicolor" is blue. We don't use green color, so it seems reasonable to remove it:
pal <- c("red", "blue")
iris_new<- filter(iris, Species == "setosa" | Species == "versicolor")
p <- plot_ly(data = iris_new, x = ~Sepal.Length, y = ~Petal.Length,
color = ~Species, colors = pal)
p
The result, obviously, should be the same, as in previous chunk of code, but in fact it isn't: the blue color is replaced by magenta, and that is very strange.
I think this is probably just because you have a 2 colour palette mapped to a 3 level factor - until you drop the unused level from the
Species
factor, it's still considered an attribute of theSpecies
variable and will affect how it is plotted.Dropping the factor level makes the colours behave as you expected: