How to revert legend colors and labels

10 views
Skip to first unread message

Roberto

unread,
Feb 26, 2009, 5:26:21 PM2/26/09
to ggplot2
I have noticed similar discussions in the list but didn't find a
satisfactory answer. Consider the following code:

da <- data.frame(x=factor(1:5), a=seq(0.1,0.9,0.2), b=seq
(0.9,0.1,-0.2))
daa <- melt(da, id="x", variable_name="bin")
p <- ggplot(daa, aes(x))
mycol <- c("blue","red")
p + geom_bar(aes(weight=value, fill=bin)) + scale_colour_manual
(values=mycol)

The resulting bars have blue over red and the legend has red ("a")
over blue ("b"). How do I make the legend show blue("b") over red
("a"), to be in the same order as the bars? I tried
value=rev(mycol), breaks = c("b","a")
to no effect.

Thanks,

Roberto

James Howison

unread,
Feb 26, 2009, 8:08:03 PM2/26/09
to ggplot2

On 26 Feb 2009, at 5:26 PM, Roberto wrote:

>
> I have noticed similar discussions in the list but didn't find a
> satisfactory answer. Consider the following code:
>
> da <- data.frame(x=factor(1:5), a=seq(0.1,0.9,0.2), b=seq
> (0.9,0.1,-0.2))
> daa <- melt(da, id="x", variable_name="bin")
> p <- ggplot(daa, aes(x))
> mycol <- c("blue","red")
> p + geom_bar(aes(weight=value, fill=bin)) + scale_colour_manual
> (values=mycol)

(btw you meant scale_fill_manual above, I'm sure).

> The resulting bars have blue over red and the legend has red ("a")
> over blue ("b"). How do I make the legend show blue("b") over red
> ("a"), to be in the same order as the bars? I tried
> value=rev(mycol), breaks = c("b","a")
> to no effect.

This also doesn't help:

daa$bin <- factor(daa$bin,levels=c("b","a"), ordered=T)

You can swap around which color is drawn on top that way (red over
blue), but the legend swaps as well, so that it is the opposite of
what you want (which is the legend in the same order as the stacked
bars).

Hopefully others have the answer.

--J

hadley wickham

unread,
Feb 26, 2009, 11:39:58 PM2/26/09
to Roberto, ggplot2

It looks like a bug in scale_manual. Breaks should control the legend
order, as in the following example:

p + geom_bar(aes(weight=value, fill=bin)) + scale_fill_hue(breaks=c("b","a"))
p + geom_bar(aes(weight=value, fill=bin)) + scale_fill_hue(breaks=c("a","b"))

I'll it to my to do list.

Hadley

--
http://had.co.nz/

Reply all
Reply to author
Forward
0 new messages