1
votes

I can't seem to be able to fill a boxplot by a continuous value using color brewer, and I know it must just be a simple swap of syntax somewhere, since I can get the outlines of the boxes to adjust based on continuous values. Here's the data I'm working with:

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)
)

I want to make a paneled boxplot, ordered by median "value", with the depth of color fill for each box increasing with "value" (I know this is redundant, but bear with me for the sake of the example)

(Ordering the data):

orderindex <- order(as.numeric(by(data$value, data$animals, median)))
data$animals <- ordered(data$animals, levels=levels(data$animals)[orderindex])

If I create the boxplot with panels, I can adjust the color of the outlines:

library(ggplot2)
first <- qplot(animals, value, data = data, colour=animals)
second <- first + geom_boxplot() + facet_grid(~region)
third <- second + scale_colour_brewer()
print(third)

But I want to do what I did to the outlines, but instead with the fill of each box (so each box gets darker as "value" increases). I thought that it might be a matter of putting the "scale_colour_brewer()" argument within the aesthetic argument for geom_boxplot, ie

second <- first + geom_boxplot(aes(scale_colour_brewer())) + facet_grid(~region)

but that doesn't seem to do the trick. I know it's a matter of positioning for this "scale_colour_brewer" argument; I just don't know where it goes!

(there is a similar question here but it's not quite what I'm looking for, since the colors of the box don't increase along a spectrum/gradient with some continuous value; it looks like these values are basically factors: Add color to boxplot - "Continuous value supplied to discrete scale" error, and the example at the ggplot site with the cars package: http://docs.ggplot2.org/0.9.3.1/geom_boxplot.html doesn't seem to work when I set "fill" to "value" ... I get the error: Error in unit(tic_pos.c, "mm") : 'x' and 'units' must have length > 0) )

1

1 Answers

3
votes

If you need to set fill for the boxplots then instead of color=animals use fill=animals and the same way replace scale_color_brewer() with scale_fill_brewer().

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

enter image description here