Define the order of palette colors in R Plotly

I am trying to create a series of Plotly plots using a function. I created a color palette for them. The datasets I'm using have a different number of grouping factors, and I want them to use the colors in the order you specify, but it seems to pick a different order depending on how many factors there are. Is there an easy way to fix this? Do I need to create a function? Thank!

An illustrative example of the problem A visual example of the problem

library(plotly)
#Some example data
x <- 1:10
g <- c("A", "B", "C", "D", "E")
g2 <- c("A", "B")
g3 <- c("A", "B", "C")
y <- 1:20
df <- as.data.frame(cbind(x,g,y))
df2 <- as.data.frame(cbind(x,g2,y))
df3 <- as.data.frame(cbind(x,g3,y))

#Color palette
pal <- c('blue','yellow','green', 'pink', 'black')

#In this plot the order is as in the pal object, this is what I want.
plot1 <- plot_ly(data=df, x=~x, y=~y,
                 type = "bar", color=~g, colors =pal)
plot1

#In this plot uses the first and the fifth in the pal object
# and I would like to be the first and second colors.
plot2 <- plot_ly(data=df2, x=~x, y=~y,
                 type = "bar", color=~g2, colors =pal)
plot2

#In this one uses the first, the third and the fifth in that order
# and I would like to be the first, second and third colors.
plot3 <- plot_ly(data=df3, x=~x, y=~y,
                 type = "bar", color=~g3, colors =pal)
plot3

      

+3


source to share


1 answer


One option is to use colors = pal [1: length (g2)] (for the second case):

enter image description here



Or you can match color to factor levels.

+2


source







All Articles