开发者

Sorting of categorical variables in ggplot

开发者 https://www.devze.com 2023-03-03 18:18 出处:网络
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

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开发者_JS百科),]
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

Sorting of categorical variables in ggplot


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:

qplot(numbers, reorder(letters, numbers), data=trial)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号