简体   繁体   English

用ggplot2中的2种不同颜色填充backgroup

[英]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. 我有一个小程序,我想用数据中的b值(> 0和<0)或因子d(m和n)用2种不同的颜色填充图组。

Is it possible in ggplot2? ggplot2中可能吗?

EDIT: Misunderstood question of OP --- Using panels and geom_rect you can approach to some extent what you want. 编辑:OP的一个被误解的问题---使用面板和geom_rect您可以在某种程度上解决您想要的问题。 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 有关类似问题,请参见此处: GGplot2中面板背景的条件格式

EDIT2: introduced another variable (panel) thus faceting occurs no longer on the basis of b and looks nicer 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)

在此处输入图片说明

@CMichael, thanks a lot. @CMichael,非常感谢。 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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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