问题描述
好日子,我希望使用ggplot2生成图形,但不使用默认分类变量(按字母顺序,以脚本:字母表示),而是使用连续变量的相关值(在脚本:数字中)。下面是一个脚本示例:
pre $ library $ ggplot2
trial trial trial.plot< -qplot(x =数字,y =字母,数据=审判)
trial.plot
trial trial.plot< -qplot(x = numbers,y = letters,data = trial)
trial.plot
trial.plot + stat_sort(variable = numbers)
最后一行不行。
stat_sort 不存在,所以它不会像你想象的那样工作。幸运的是, reorder()
函数根据第二个变量的值对分类变量的级别进行重新排序。我认为这应该做你想做的:
trial.plot< - qplot(x = numbers,y = reorder ,数字),data = trial)
trial.plot
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.
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 the reorder()
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:
trial.plot <- qplot( x = numbers, y = reorder(letters, numbers), data = trial)
trial.plot
这篇关于ggplot中的分类变量排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!