2017-08-02 67 views
1

我想要一個多面barplot。表示總值的小節必須是紅色的,其他的則是藍色的。
總值由Desc1 =「 - 」表示。 我有以下代碼:方面barplot不尊重colorvalues

#df contains the following data:                           
#Year;Maingroup;Desc1 ;Desc2  ;Value 
#2017;A    ;1  ;A1    ;10 
#2017;A    ;2  ;A2    ;20 
#2017;A    ;-  ;AT    ;30 
#2017;B    ;10  ;B10   ;100 
#2017;B    ;20  ;B20   ;200 
#2017;B    ;-  ;BT    ;300                          
#2017;C    ;11  ;C100   ;53 
#2017;C    ;22  ;C200   ;54 
#2017;C    ;-  ;CT    ;107 

#add a new description                             
df <- df %>% unite (Oms,Desc1,Value,sep=' ',remove=FALSE) 
#add color indication 
df <- df %>% mutate(colv=(ifelse(Desc1=="-  ","Red","Blue"))) 
#sort into descending order 
df <- df %>% arrange(desc(Value)) 
#plot horizontal barchart 
ggplot(df, aes(x=Desc2,y=Value))+ 
geom_bar(position=position_dodge(),stat="identity",fill=df$colv)+ 
facet_grid(~Maingroup,scale="free")+ 
coord_flip() 

但R不着色的方法不對的吧。 Wrong bar colors 我在做什麼錯?

+1

我猜你需要把'補= .. .'在'aes()'內部調用 –

+0

感謝超級響應,試過了,但沒有奏效 – Rense

+0

然後,我建議你使用'dput'發佈實際數據的最小示例(處理後),這樣我們就可以嘗試看看有什麼不對 –

回答

0

你必須使用內AES()在開始時填充= COLV,然後用scale_fill_manual()來定義這樣的顏色:

ggplot(df, aes(x=Desc2,y=Value, fill=colv))+ 
geom_bar(position=position_dodge(),stat="identity") + 
scale_fill_manual(values = c("blue", "red")) + 
facet_grid(~Maingroup,scale="free") + 
coord_flip()