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)
我有一个条形图,我想要用数据中的b值(> 0和&lt; 0)或因子d(m和n)填充2种不同颜色的情节背景组。
是否可以在ggplot2中使用?
答案 0 :(得分:1)
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)
答案 1 :(得分: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)