0
votes

I'm having a difficult time understanding how factor labels interact with legends. How do I set the order of levels so that the ggplot2 system creates a legend that I envision?

In the below code, the plot associate the Reds with the negative side of the interval and the blues with the positive.

require(ggplot2)
require(RColorBrewer)

set.seed(1492)  #discovery!
sample = data.frame(x = c(1:20), y = 1, obs = runif(20, -150, 150))
the.breaks = seq(-100, 100, by = 20)

sample$interval = factor(findInterval(sample$obs, vec = the.breaks, all.inside = TRUE), 
    labels = the.breaks, levels = c(1:length(the.breaks)))

pal = rev(brewer.pal(11, "RdBu"))

p = ggplot(sample, aes(x, y, colour = interval))
p = p + geom_point(size = 10)
p = p + scale_colour_manual(values = pal, limits = the.breaks, labels = the.breaks)
p = p + guides(colour = guide_legend(override.aes = list(size = 3, shape = 19)))
p

This works fine, but I really don't like the

pal = rev(brewer.pal(11, "RdBu"))

statement - seems inelegant. I'd like to be able to replace the use of scale_colour_manual with something like

p = p + scale_colour_brewer(palette="RdBu", type="div", limits = the.breaks, labels = the.breaks)

but when I do, the Reds get associated with the positive end.

1

1 Answers

0
votes

You can order your factor levels in any way you like, this should help you get them the right colours. Try this explanation or any others out there on ordering factor levels. Note that the opts command in the blog post is out-dated.

Also check out this question.

And this one as well.