Etienne Low-Décarie
Etienne Low-Décarie

Reputation: 13443

Sorting of categorical variables in ggplot

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.

Upvotes: 7

Views: 5902

Answers (2)

mcpeterson
mcpeterson

Reputation: 5134

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)

Upvotes: 0

Chase
Chase

Reputation: 69201

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

enter image description here

Upvotes: 9

Related Questions