Reputation: 2190
I'm trying to re-order a categorical/non-numeric y-axis by the number of observations associated with each value.
I import a table that looks like this:
View(ranges)
ID | Time | Value | obs
B1 | 1:11 | 1 | 91
B1 | 1:12 | 2 | 91
...
U30 | 2:22 | 99 | 101
Then reorder:
ranges <- ranges[with(ranges, order(obs, ID)), ]
Then plot:
p <- ggplot(ranges, aes(x=Time, y=ID, fill=Value))
p <- p + geom_tile(colour = "white")
p
But the order on the y-axis does not reflect the number observations per ID.
How can I sort the y-axis to reflect the frequency of the ID in the dataframe? Thanks kindly.
Sample data, comma delimited:
ID,DATE,VALUE,OBS
B9148,41275,0133,7
B9148,41276,3344,7
B9148,41277,7907,7
B9148,41278,2052,7
B9148,41279,6617,7
B9148,41280,9411,7
B9148,41281,6302,7
U1821,41275,7585,11
U1821,41276,5086,11
U1821,41277,5731,11
U1821,41278,5358,11
U1821,41279,9977,11
U1821,41280,1446,11
U1821,41281,2728,11
U1821,41282,5369,11
U1821,41283,8171,11
U1821,41284,5817,11
U1821,41285,0166,11
F7484,41275,8971,10
F7484,41276,5635,10
F7484,41277,8629,10
F7484,41278,5832,10
F7484,41279,4775,10
F7484,41280,4519,10
F7484,41281,1527,10
F7484,41282,7861,10
F7484,41283,5713,10
F7484,41284,0824,10
S3804,41275,0573,4
S3804,41276,0123,4
S3804,41277,8468,4
S3804,41278,6258,4
B8088,41275,9117,7
B8088,41276,8489,7
B8088,41277,0902,7
B8088,41278,8684,7
B8088,41279,7229,7
B8088,41280,3587,7
B8088,41281,0907,7
Upvotes: 1
Views: 489
Reputation: 25608
You can do this either manually:
ranges$ID <- factor(ranges$ID, levels=c("S3804", "B8088", "B9148", "F7484", "U1821"))
or more or less automatically:
ranges$ID <- factor(ranges$ID, levels=as.character(unique(ranges$ID)))
The basic idea of why this happens is because factor levels are stored separately and are not affected by ordering, whereas ggplot plots level by level.
You can also refer to this question for a demo on this concept.
Is this what you wanted? Note that if you want reverse order, just add rev() before as.character().
Upvotes: 1