Skip to content
Prev 140130 / 398502 Next

ggplot2 - legend for fill coulours

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