Sorting categorical variables in ggplot

Good afternoon, I want to create graphics using ggplot2, but not using the default sorting of the categorical variable (in alphabetical order, in script: letters), but using the associated value of the 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.

+7
source share
2 answers

I am sure that stat_sort does not exist, so it is not surprising that it does not work, as you think. Fortunately, there is a reorder() function that reorders the level of a categorical variable depending on the values ​​of the second variable. I think this should do what you want:

 trial.plot <- qplot( x = numbers, y = reorder(letters, numbers), data = trial) trial.plot 

enter image description here

+8
source

If you can be more specific about how you want it to look, I think the community can improve my answers, no matter what you are looking for:

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

All Articles