简体   繁体   中英

fill backgroup with 2 different colours in ggplot2

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)

在此处输入图片说明

I have a barplot, i woule like to fill the plot backgroup with 2 different colours with respect to the b values (> 0 and < 0) or factor d (m and n) in the data.

Is it possible in ggplot2?

EDIT: Misunderstood question of OP --- Using panels and geom_rect you can approach to some extent what you want. Some more tweaking may be necessary but ideally you have your own ideas. See here for a similar question: Conditional formatting of panel background in GGplot2

EDIT2: introduced another variable (panel) thus faceting occurs no longer on the basis of b and looks nicer

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)

在此处输入图片说明

@CMichael, thanks a lot. from your answer, i have got exactly what i want after a lit modification.

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM