ggplot 中分类变量的排序
美好的一天,我希望使用 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)
最后一行不起作用。
Good day, I wish to produce a graphic using ggplot2, but not using its default sorting of the categorical variable (alphabetically, in script: letters), but using the associated value of a continuous variable (in script: number) .
Here is an example script:
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)
The last line does not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我非常确定
stat_sort
不存在,因此它无法按照您的预期工作也就不足为奇了。幸运的是,有一个 reorder() 函数,它可以根据第二个变量的值对分类变量的级别进行重新排序。我认为这应该满足您的要求:I'm pretty sure
stat_sort
does not exist, so it's not surprising that it doesn't work as you think it should. Luckily, there's thereorder()
function which reorders the level of a categorical variable depending on the values of a second variable. I think this should do what you want:如果您可以更具体地说明您希望它的外观,我认为社区可以改进我的答案,无论这是否是您正在寻找的:
If you could be more specific about how you want it to look, I think the community could make improvements on my answer, regardless is this what you are looking for: