2014-10-05 50 views
2

我使用以下代碼創建一個條形圖,每個條形圖根據其所屬的組進行着色。如何根據分組變量對ggplot中的結果進行排序

library("ggplot2") 
df <- data.frame(ID=c(5,2,3,6,1,4),Score=c(24.8,33.2,55.21,19.21,41.99,15.23),Gender=c("Man","Woman","Woman","Man","Man","Woman")) 
ggplot(df, aes(x=ID, y=Score, color=Gender)) + geom_bar(stat="identity") 

這產生如下的圖

enter image description here

現在,我想是實現排序,其中條顯示,關於性別可變初級和次級上的順序ID變量。我在StackExchange上查找了答案,但是從我所知道的來看,它們大多數只處理y變量的排序。 (請注意,這是一個最簡單的例子,我真正的例子是非常大的,因此,我想找到一種方法來命令我不需要的所有東西,例如,手動輸入每個ID號。)

回答

7

你可以使用interaction做到這一點(爲了男人和女人更好的區分,我用的fill代替color):

ggplot(df, aes(x=interaction(ID,Gender), y=Score, fill=Gender)) + 
    geom_bar(stat="identity") + 
    scale_x_discrete("ID",breaks=interaction(df$ID,df$Gender),labels=df$ID) + 
    theme_bw() + 
    theme(axis.title = element_text(size=14,face="bold"), axis.text = element_text(size=12)) 

這給: enter image description here


作爲替代方案,你也可以使用磨製:

ggplot(df, aes(x=factor(ID), y=Score, fill=Gender)) + 
    geom_bar(stat="identity") + 
    scale_x_discrete("ID",breaks=df$ID,labels=df$ID) + 
    facet_grid(.~Gender, scales="free_x") + 
    guides(fill=FALSE) + theme_bw() + 
    theme(axis.title=element_text(size=14,face="bold"), axis.text=element_text(size=12), 
     strip.text=element_text(size=12,face="bold"), strip.background=element_rect(fill=NA,color=NA)) 

這給: enter image description here

+1

謝謝!優秀的造型額外的榮譽! – Speldosa 2014-10-05 11:11:56

相關問題