Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate palettes for facets in ggplot facet_grid

Tags:

r

ggplot2

facet

Question
How can I use a different color palette for each facet? Ideally I would like to have a generic legend in gray to serve as a reference.

I'm working on a visualization using ggplot's facet_grid. The layout is fine, but I would like to use a distinct color palette for every row in the grid. My goal is to use a similarly-shaded gradient for every palette and then tie them together with a grayscale legend. I'm would like to do this to maintain internal color-coding consistency within a larger set of graphics. It would amazing to be able to still use facet_grid instead of using grobs (with which I am vastly less familiar).

I've included an example to work with using the diamonds data set and an arbitrary grouping to approximate what my data looks like.

data(diamonds) 
diamonds$arbitrary = sample(c("A", "B", "C"), length(diamonds$cut), replace = TRUE)

blues = brewer.pal(name="Blues", n=3)
greens = brewer.pal(name="Greens", n=3)
oranges = brewer.pal(name="Oranges", n=3)
purples = brewer.pal(name="Purples", n=3)

ggplot(diamonds) + 
  geom_bar(aes(x = clarity, stat = "bin", fill = arbitrary, group = arbitrary)) + 
  facet_grid(cut~.) + 
  # Here I assign one palette... is this where I could also
  # designate the other palettes?
  scale_fill_manual(values = blues)

enter image description here

Thank you!

like image 597
Nancy Avatar asked Nov 30 '22 17:11

Nancy


1 Answers

faking a colour scale with transparency might be your best option, unless you're willing to combine multiple pieces at the grid/gtable level.

ggplot(diamonds) + 
  geom_bar(aes(x = clarity, stat = "bin", fill = cut, 
               alpha=arbitrary, group = arbitrary)) + 
  facet_grid(cut~.) + 
  scale_fill_manual(values = brewer.pal(name="Set1", n=5), guide="none") +
  scale_alpha_manual(values=c(0.8, 0.6, 0.4))

enter image description here

like image 144
baptiste Avatar answered Dec 04 '22 13:12

baptiste