Plotly is blending palette colors in R

250 views Asked by At

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.

1

There are 1 answers

2
Marius On BEST ANSWER

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 the Species variable and will affect how it is plotted.

Dropping the factor level makes the colours behave as you expected:

iris_new<- filter(iris, Species == "setosa" | Species == "versicolor") %>%
    mutate(Species = droplevels(Species))
p <- plot_ly(data = iris_new, x = ~Sepal.Length, y = ~Petal.Length, 
             color = ~Species, colors = pal)
p