2
votes

i'm trying to define a specific color palette for each individual trace of a chart in plotly in r. my code is as follows:

library(ggplot2)
library(dplyr)
library(plotly)
colors_1 <- c("#2e71c9","#ffb728")
colors_2 <- c("#4f4f4f","#000000")

data_subset_1 <- 
    diamonds %>% 
    filter(clarity %in% c("VVS2", "VS1")) %>% 
    mutate(cut = as.character(cut)) %>% 
    count(cut, clarity)

data_subset_2 <- 
    diamonds %>% 
    filter(clarity %in% c("SI1", "IF")) %>% 
    mutate(cut = as.character(cut)) %>% 
    count(cut, clarity)

plot_ly() %>% 
    add_bars(data = data_subset_1, x = ~cut, y = ~n, color = ~clarity, colors = colors_1) %>% 
    add_bars(data = data_subset_2, x = ~cut, y = ~n, color = ~clarity, colors = colors_2)

the bars of the first trace should be in blue and orange, the 2nd trace in grey and black, but clearly they all are all in color. if i remove the colors = colors_2 from the second trace, it does not even change anything at all. it seems the colors defined in the first trace are being used to calculate a color palette that is used for all traces of the plot, but i'd like to specifically assign color palettes.

1

1 Answers

1
votes

Try the following:

cols <- setNames(c("#2e71c9","#ffb728", "#CCDDDD","#000000"), 
                 c("VVS2", "VS1", "SI1", "IF"))

plot_ly() %>% 
  add_bars(data = data_subset_1, x = ~cut, y = ~n, color = ~clarity, colors = cols) %>% 
  add_bars(data = data_subset_2, x = ~cut, y = ~n, color = ~clarity)

enter image description here