在ggplot中对分类变量进行排序

Eti*_*rie 7 r ggplot2

美好的一天,我希望使用ggplot2生成图形,但不使用其默认的分类变量排序(按字母顺序排列,在脚本中:字母),但使用连续变量的相关值(在脚本中:数字).

这是一个示例脚本:

library(ggplot2)
trial<-data.frame(letters=letters, numbers=runif(n=26,min=1,max=26))
trial<-trial[sample(1:26,26),]
trial.plot<-qplot(x=numbers, y=letters, data=trial)
trial.plot
trial<-trial[order(trial$numbers),]
trial.plot<-qplot(x=numbers, y=letters, data=trial)
trial.plot
trial.plot+stat_sort(variable=numbers)
Run Code Online (Sandbox Code Playgroud)

最后一行不起作用.

Cha*_*ase 8

我很确定stat_sort不存在,所以它不会像你认为的那样工作也就不足为奇了.幸运的是,有一个reorder()函数可以根据第二个变量的值重新排序分类变量的级别.我认为这应该做你想要的:

trial.plot <- qplot( x = numbers, y = reorder(letters, numbers), data = trial)
trial.plot
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述