簡體   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)

在此處輸入圖片說明

我有一個小程序,我想用數據中的b值(> 0和<0)或因子d(m和n)用2種不同的顏色填充圖組。

ggplot2中可能嗎?

編輯:OP的一個被誤解的問題---使用面板和geom_rect您可以在某種程度上解決您想要的問題。 可能需要更多調整,但理想情況下您有自己的想法。 有關類似問題,請參見此處: 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)

在此處輸入圖片說明

@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)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM