2016-06-16 76 views
1

我有一個學生表看起來像這樣,如何在R中使用ggplot繪製排序的頻率 - 條形圖?

StudentID SectorID ClassID 
1   A Team_1 Class_1 
2   A Team_1 Class_1 
3   B Team_1 Class_1 
4   B Team_2 Class_1 
5   B Team_2 Class_1 
6   A Team_2 Class_1 
7   A Team_3 Class_1 
8   C Team_3 Class_2 
9   C Team_3 Class_2 
10   C Team_3 Class_2 
11   C Team_3 Class_2 
12   C Team_1 Class_2 
13   D Team_1 Class_2 
14   D Team_1 Class_2 

你可以看到這個這個,

stg <- data.frame(StudentID = c(rep("A", 2), rep("B", 3), rep("A", 2), rep("C", 5), rep("D", 2) ), 
        SectorID = c(rep("Team_1", 3), rep("Team_2", 3), rep("Team_3", 5), rep("Team_1", 3)),    
        ClassID  = c(rep("Class_1", 7), rep("Class_2", 7))    
) 


stg 

ggplot(stg, aes(x = stg$StudentID)) + geom_bar() 

現在,我想實現一個排序的條形圖。 C(頻率爲5)首先出現,依此類推。你可以爲此遮光一下嗎?感謝您的時間。

回答

2

您需要將studentID設置爲具有所需順序級別的因子。此代碼將做到這一點

cnt <- plyr::count(stg$StudentID) 
stg$StudentID <- factor(stg$StudentID, 
    levels = cnt$x[order(cnt$freq, decreasing = TRUE)]) 

ggplot(stg, aes(x = StudentID)) + geom_bar() 
1

你能做到這一點..

ggplot(stg, aes(x = reorder(StudentID,StudentID,function(x)-length(x)))) + geom_bar() 

enter image description here