如何在R中用ggplot绘制排序的频率条形图?

时间:2016-06-16 08:15:41

标签: r ggplot2 bar-chart frequency

我的学生表看起来像这样,

   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 个答案:

答案 0 :(得分: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 :(得分:1)

你可以这样做..

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

enter image description here