在R中的ggplot中排序x轴

时间:2014-07-27 15:47:54

标签: r

我正在使用以下数据&代码:

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 但是,我需要按照正确的数字顺序('一个','两个','三个&#)订购x轴因子('单词') 39;等x轴)。我怎样才能做到这一点?谢谢你的帮助。

2 个答案:

答案 0 :(得分:3)

技巧是在因子创建期间指定标签顺序

> 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

上面的示例通过数据表中的value列对条形图进行排序。如果您需要根据标签的字面含义订购条形,则必须手动指定:

> lvls = c('one', 'two', .....)

答案 1 :(得分:2)

按数字列中的值重新排序。

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

如果你谷歌“在ggplot中重新排序x轴”,你将获得大约100次点击,解释如何执行此操作。