开发者

Colours gradients with stacked bar charts in ggplot2

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 thoug开发者_高级运维ht 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


Hadley's suggestion works.

p1 + scale_fill_brewer(type = "div")


You might wanna try: scale_fill_brewer(palette="RdYlGn").

I'm doing a similar code and manual isn't working very well.

With this scale_fill_brewer you can use palette colors: RdYlGn, Reds, etc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜