1
votes

I have the following plot with plotly :

library(plotly)
library(dplyr)
ggplot2::diamonds %>% count(cut, clarity) %>%
  plot_ly(x = ~cut, y = ~n, color = ~clarity,colors = 'Blues')

Right now I only have one color palette 'Blues' for all groups. How can i customize it so I have one color palette per group ? For example, I would like the color palette

  • 'Blues' for the level 'Fair'
  • 'Greens' for the level 'Good'
  • 'Reds' for the level 'Very Good'
  • 'Purples' for the level 'Premium'
  • 'Greys' for the level 'Ideal'
1

1 Answers

1
votes

The following code seems to work with a static ggplot2 plot:

library(tidyverse)
library(plotly)
library(RColorBrewer)

sPalette <- c("Blues", "Greens", "Reds", "Purples", "Greys") %>% 
              sapply(., function(x) brewer.pal(8, name = x)) %>% 
              as.vector

diamonds %>% 
  count(cut, clarity) %>% 
  ggplot(., aes(x = cut, y = n, fill = interaction(clarity, cut, sep = " - "))) + 
    geom_bar(stat = "identity", position = "dodge") + 
    scale_fill_manual(values = sPalette, guide = F) + 
    theme_minimal()

This is the result:

enter image description here

The corresponding plot_ly code produces bars which have a wide space between them, and I'm not exactly sure why that's the case:

diamonds %>% 
  count(cut, clarity) %>%
  plot_ly(x = ~cut, y = ~n, color = ~interaction(clarity, cut, sep = " - ") , colors = sPalette)

enter image description here

It turns out however, that ggplotly does work:

p <- diamonds %>% 
       count(cut, clarity) %>% 
       ggplot(., aes(x = cut, y = n, fill = interaction(clarity, cut, sep = " - "))) + 
         geom_bar(stat = "identity", position = "dodge") + 
         scale_fill_manual(values = sPalette, guide = F) + 
         theme_minimal()
ggplotly(p)

enter image description here