2014-01-25 41 views
1
test<-data.frame(a=c('1','1','2','2'),b=c(2,-2,4,-3),d=c('m','n','m','n')) 
p+geom_bar(position=position_dodge(),stat='identity',fill='deeppink',colour='black',width=0.5) 

enter image description here與2種不同的顏色的補backgroup在GGPLOT2

我有一個barplot,我woule喜歡填充情節backgroup與2種不同的顏色相對於b值(> 0和< 0)或數據中的因子d(m和n)。

ggplot2可能嗎?

回答

1

編輯:誤解OP的問題---使用面板和geom_rect你可以在某種程度上達到你想要的。一些更多的調整可能是必要的,但理想情況下你有自己的想法。在這裏看到類似的問題:Conditional formatting of panel background in GGplot2

EDIT2:引入另一個變量(面板),從而刻面不再出現b的基礎上,看起來更好

require(ggplot2) 
test<-data.frame(a=c('1','1','2','2'),b=c(2,-2,4,-3),d=c('m','n','m','n')) 
x <- rep(seq(1,2),2) 
test$panel <- x 
test$colorindicator = ifelse(test$b<0,"negative","positive") 
p=ggplot(data=test,aes(x=a,y=b)) 
p = p + geom_rect(aes(fill = colorindicator), xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, alpha = 1) 
p = p + geom_bar(fill='deeppink',color="black",position=position_dodge(),stat='identity',width=0.5) 
p = p + facet_grid(.~panel,scales="free") 
print(p) 

enter image description here

+0

感謝您的回覆。但我想改變情節backgroup顏色,而不是酒吧填充顏色。 – user36102

1

@CMichael,由於一許多。從你的回答中,我已經得到了我想要的東西,經過點亮的修改。

require(ggplot2) 
test<-data.frame(a=c('1','1','2','2'),b=c(2,-2,4,-3),d=c('m','n','m','n')) 
p=ggplot(data=test,aes(x=a,y=b)) 
p = p + geom_rect(fill = 'red', xmin = -Inf, xmax = Inf, ymin =0, ymax = Inf, alpha =0.05) 
p = p + geom_rect(fill = 'green', xmin = -Inf, xmax = Inf, ymin =-Inf, ymax = 0, alpha =0.05) 
p = p + geom_bar(fill='deeppink',color="black",position=position_dodge(),stat='identity',width=0.5) 
print (p) 

enter image description here

+0

好的 - 現在我明白了:) – CMichael