1

I am using following data & code:

ddf = structure(list(number = 1:20, words = structure(c(10L, 20L, 17L, 
6L, 5L, 13L, 11L, 1L, 8L, 15L, 3L, 18L, 16L, 7L, 4L, 14L, 12L, 
2L, 9L, 19L), .Label = c("eight", "eighteen", "eleven", "fifteen", 
"five", "four", "fourteen", "nine", "nineteen", "one", "seven", 
"seventeen", "six", "sixteen", "ten", "thirteen", "three", "twelve", 
"twenty", "two"), class = "factor"), value = c(0.34420683956705, 
0.612443619407713, 0.7042224498, 0.832921771565452, 0.351153316209093, 
0.622333734529093, 0.932609781855717, 0.584015318658203, 0.968014082405716, 
0.141673753270879, 0.787956288317218, 0.852732613682747, 0.411922389175743, 
0.781018695561215, 0.474310273537412, 0.701303839450702, 0.339094886090606, 
0.442493645008653, 0.941094532376155, 0.135925917653367)), .Names = c("number", 
"words", "value"), row.names = c(NA, -20L), class = "data.frame")

 head(ddf)
  number words     value
1      1   one 0.3442068
2      2   two 0.6124436
3      3 three 0.7042224
4      4  four 0.8329218
5      5  five 0.3511533
6      6   six 0.6223337


ggplot(ddf)+geom_bar(aes(x=words, y=value), stat="identity")

enter image description here However, I need to order the x-axis factors ('words') in proper numeric order ('one', 'two', 'three' etc on x-axis). How can I achieve this? Thanks for your help.

rnso
  • 23,686
  • 25
  • 112
  • 234

2 Answers2

3

The trick is to specify label order during factor creation

> lix = order(ddf$value)
> lvls = ddf$words[lix]
> ddf$words = factor(ddf$words, levels=lvls)
> ggplot(ddf) + geom_bar(aes(x=words, y=value), stat='identity')
> 

sorted barplot

The above example orders the bars by the value column in the data table. If you need to order the bars according to the literal meaning of the labels, you will have to specify it manually:

> lvls = c('one', 'two', .....)
Boris Gorelik
  • 29,945
  • 39
  • 128
  • 170
2

This reorders by the values in the number column.

library(ggplot2)
ddf$words <- reorder(ddf$words,ddf$number)
ggplot(ddf)+geom_bar(aes(x=words, y=value), stat="identity")

If you Google "reordering x axis in ggplot" you'll get about 100 hits that explain how to do this.

jlhoward
  • 58,004
  • 7
  • 97
  • 140
  • Above command is not altering my graph. Here also reorder command is not working on my system as in my other post: http://stackoverflow.com/questions/24981042/why-factor-variable-is-not-reordering-in-r – rnso Jul 27 '14 at 16:30
  • The code above reorders the factor `ddf$words` based on the values in `ddf$number`. If that's not what you are asking for, can you please explain it differently as an edit to your question. – jlhoward Jul 27 '14 at 17:17
  • For some reason, reorder function is not working on my system, as mentioned in my comment above. Is there any other method? – rnso Jul 27 '14 at 17:35