2

I have a student table that look like this,

   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

You can see this by this,

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

Now, I want to achieve a sorted barchart. Where C (with frequency 5) will appear first, and so on. Could you please shade some lights on this? Thank you for your time.

Droid-Bird
  • 1,417
  • 5
  • 19
  • 43

2 Answers2

4

You could do this..

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

enter image description here

ArunK
  • 1,731
  • 16
  • 35
3

You need to make studentID into a factor with the levels in the desired order. This code will do that

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()
Richard Telford
  • 9,558
  • 6
  • 38
  • 51