[R] ggplot2 - legend for fill coulours

From: Pedro de Barros <pbarros_at_ualg.pt>
Date: Sun, 23 Mar 2008 12:02:09 +0000


Dear All,

I am trying to build a stacked bar plot, where I define the colours to use.

I have asked this before, and I was using a solution in http://thread.gmane.org/gmane.comp.lang.r.general/100649/focus=100673 (thanks, Thierry).

However, it looks this works only when the data are in the sequence of the levels in the factor defining the fill colours. When the sequence is different, the legend gets "scrambled", in that the order of the colours does not match the labels.

My code is below. Can anyone tell me how to get around this? (R 2.2.6 for Windows, ggplot2 version 2_0.5.7)

Thanks,
Pedro
library(ggplot2)
Data:

> plotdata2

    x y group

1  1 0.1 grey30
2  2 0.2 grey30
3  3 0.3 grey10
4  4 0.4 grey90
5  1 0.1 grey30
6  2 0.2 grey60
7  3 0.3 grey60
8  4 0.4 grey90
9  1 0.1 grey60
10 2 0.2 grey10
11 3 0.3 grey90
12 4 0.4 grey30
13 1 0.1 grey90
14 2 0.2 grey60
15 3 0.3 grey10
16 4 0.4 grey10

> levels(plotdata2$group)

[1] "grey10" "grey30" "grey60" "grey90"
> as.numeric(plotdata2$group)

  [1] 2 2 1 4 2 3 3 4 3 1 4 2 4 3 1 1

Code:
plot0<-ggplot()
layer1<-layer(data=plotdata2, mapping=aes_string(x='x',y='y', fill='group'),geom='bar', stat='identity', position='stack') scaleFill<-scale_fill_identity(labels=levels(plotdata2$group), guide='tile', name='Group')
scaleY<-scale_y_continuous(limits=c(0,4), expand=c(0,0)) plot1<-plot0+layer1 +scaleFill +scaleY

plot1



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sun 23 Mar 2008 - 12:05:04 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 01 Apr 2008 - 19:30:25 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive