1

I am doing a boxplot in ggplot2, but I have been unable to find a way to deal with multiple colors across a 3 x 3 factor design.

This is an example code what I have able to do (using as a guide this thread):

library(ggplot2)

data <- data.frame(
  value = sample(1:50),
  animals = sample(c("cat","dog","zebra"), 50, replace = TRUE),
  region = sample(c("forest","desert","tundra"), 50, replace = TRUE)
)

ggplot(data, aes(animals, value)) + geom_boxplot(aes(fill = animals)) +
  facet_grid(~region) + scale_fill_brewer()

I am being able to use the color blue scale for the the categories: desert, forest and tundra. You can see the output here.

However, what I would like to use a diferent color scale for each one this categories. For example: yellow scale for dessert, green scale for forest and blue for tundra. Thanks!

Mako212
  • 6,787
  • 1
  • 18
  • 37

2 Answers2

1

The easiest way is to use alpha for transparency as a dimension, as suggested at the possible dupe. It's a little different to get a nice legend for boxplots, here's a worked example. (Though, since they have x-labels, you could probably just set guide = FALSE in the alpha scale.)

ggplot(data, aes(animals, value)) + 
  geom_boxplot(aes(fill = region, alpha = animals)) +
  facet_grid( ~ region) +
  scale_alpha_discrete(
     range = c(0.3, 0.9),
     guide = guide_legend(override.aes = list(fill = "black"))) +
  scale_fill_manual(values = c("goldenrod2", "forestgreen", "dodgerblue4"))

enter image description here

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
0

You can do this in a not-so-elegant way with data manipulation.

library(ggplot2)
library(dplyr)

data <- data.frame(value = sample(1:50),
                   animals = sample(c("cat","dog","zebra"), 50, replace = TRUE),
                   region = sample(c("forest","desert","tundra"), 50, replace = TRUE))

data <- data %>% 
  dplyr::mutate(fill = paste(animals, "-", region))

ggplot(data, aes(animals, value)) + 
  geom_boxplot(aes(fill = fill), col  = "black", show.legend = F) +
  facet_grid(~region) +
  scale_fill_manual(values = c("gold3", "green3", "blue",
                               "yellow", "green4",  "blue4",
                               "goldenrod", 'greenyellow', "dodgerblue2"))

enter image description here

bbiasi
  • 1,549
  • 2
  • 15
  • 31