2013-07-01 41 views
0

我有一個數據組,看起來像這樣,對照組:顏色使用geom_bar中的R

a<-data.frame(Strain=rep(LETTERS[1:3], each=2), 
       Mean=rnorm(6,0.5,0.1), 
       Treat=rep(letters[1:2],6)) 

而且我想使用ggplot,但具有不同的填充顏色爲應變繪製它的條形圖對應於「C」。我不知道我是否有適當的方法,只需添加具有該特定代碼的另一圖層,但表示填充的長度不正確。

b <- ggplot(data=a, aes(x=factor(Strain), y=Mean, fill=factor(Treat))) + 
    geom_bar(position='dodge', stat='identity') + 
    geom_bar(data=subset(a,a$Strain=="C"), fill=c('red','blue'), 
       position='dodge', stat='identity') 

對不起,基本的問題,但到目前爲止我還沒有能夠解決它。謝謝你的幫助!

回答

2

是否這樣?

a$treat2 <- as.character(a$Treat) 
a$treat2[a$Strain=="C"] <- paste("C",a$treat2[a$Strain=="C"],sep=".") 

#function to create ggplot default colours 
ggcolours <- function(n) force(hcl(h=seq(15, 375-360/n, length=n)%%360, c=100, l=65)) 

b <- ggplot(data=a, aes(x=Strain, y=Mean, group=Treat,fill=treat2)) + 
    geom_bar(position='dodge', stat='identity') + 
    #use scale_fill_manual to specify the colours 
    scale_fill_manual(values=c(ggcolours(2),"#FF0000","#0000FF")) 

print(b) 

enter image description here