tags:

views:

98

answers:

1

Stacked bar charts use a hue-based colour scale by default, in order to distinguish the different sections of bar. Since the factor levels corresponding to my stacks are ordered, I would like to use a gradient scale.

Here's some made-up questionnaire data

dfr <- data.frame(
  question = c("Do you like R?", "How about Stack Overflow?"),
  rubbish  = c(2, 1),
  so.so    = c(7, 9),
  yippee   = c(41, 40)
)

mdfr <- melt(dfr, measure.vars = c("rubbish", "so.so", "yippee"))

Here's a plot that works, but without the gradient colour scale

p1 <- ggplot(mdfr, aes(question, value, fill = variable)) +
  geom_bar(position = "stack") +
  coord_flip()

If I add the gradient scale, I get told that I should be using a numerical variable for it, not categorical.

p1 + scale_fill_gradient2()
#Error: Non-continuous variable supplied to scale_fill_gradient2.

If I force the fill colour variable to be numerical, then geom_bar complains that it should be stacking a categorical variable

ggplot(mdfr, aes(question, value, fill = as.integer(variable))) +
  scale_fill_gradient2() +
  geom_bar(position = "stack") +
  coord_flip()
#Error in pmin(y, 0) : object 'y' not found

Is there a way round this?

EDIT:

After sleeping on the question, I thought a manual scale might be the answer, but I can't get that working either.

cols <- c(rubbish = "red", so.so = "white", yippee = "blue")
p1 + scale_colour_manual(values = cols)
# Manual scale silently ignored
A: 

Hadley's suggestion works.

p1 + scale_fill_brewer(type = "div")
Richie Cotton