Speldosa
Speldosa

Reputation: 1970

How to sort results in ggplot according to grouping variable

I create a bar chart, with each bar colored according to what group it belongs to, using the following code.

library("ggplot2")
df <- data.frame(ID=c(5,2,3,6,1,4),Score=c(24.8,33.2,55.21,19.21,41.99,15.23),Gender=c("Man","Woman","Woman","Man","Man","Woman"))
ggplot(df, aes(x=ID, y=Score, color=Gender)) + geom_bar(stat="identity")

This generates the following graph

enter image description here

Now, what I'd like to achieve is to sort the order in which the bars appear, primary on the gender variable and secondary on the ID variable. I've searched for answers here on StackExchange, but from what I can tell, most of them deals with sorting on the y variable only.

(Note that this is a minimal example and my real example is pretty huge. Therefore, I'd like to find a way to order everything where I don't have to, for example, type in every ID number manually.)

Upvotes: 2

Views: 4112

Answers (1)

Jaap
Jaap

Reputation: 83215

You could use interaction to do that (in order to better distinguish between Man and Woman, I used fill instead of color):

ggplot(df, aes(x=interaction(ID,Gender), y=Score, fill=Gender)) + 
  geom_bar(stat="identity") +
  scale_x_discrete("ID",breaks=interaction(df$ID,df$Gender),labels=df$ID) +
  theme_bw() +
  theme(axis.title = element_text(size=14,face="bold"), axis.text = element_text(size=12))

this gives: enter image description here


As an alternative, you can also use facetting:

ggplot(df, aes(x=factor(ID), y=Score, fill=Gender)) + 
  geom_bar(stat="identity") +
  scale_x_discrete("ID",breaks=df$ID,labels=df$ID) +
  facet_grid(.~Gender, scales="free_x") +
  guides(fill=FALSE) + theme_bw() +
  theme(axis.title=element_text(size=14,face="bold"), axis.text=element_text(size=12),
        strip.text=element_text(size=12,face="bold"), strip.background=element_rect(fill=NA,color=NA))

which gives: enter image description here

Upvotes: 7

Related Questions