Home > other >  How to order axis by facet in ggplot2?
How to order axis by facet in ggplot2?

Time:07-18

I'm not able to order the x axis correctly. As an example, we can see that, in facet 2, the x-axis "140<150" is after "150<160", when it should come before. I also tried data$cut <- factor(data$cut, levels=unique(data$cut), ordered=TRUE) but it didn't work. Would there be any way to sort by group or directly in ggplot?

library(ggplot2)

data <- data.frame(Group = c(rep(1,15),rep(2,15),rep(3,18),rep(4,14)),
                          cut = c("10<20","20<30","30<40","40<50","50<60","60<70","70<80","80<90", 
                                  "90<100","100<110","110<120","120<130","130<140","150<160","160<170","10<20", 
                                  "20<30","30<40","40<50","50<60","60<70","70<80","80<90","90<100", 
                                  "100<110","110<120","120<130","130<140","140<150","150<160","10<20","20<30",  
                                  "30<40","40<50","50<60","60<70","70<80","80<90","90<100","100<110",
                                  "110<120","120<130","130<140","150<160","170<180","190<200","220<230","290<300",
                                  "10<20","20<30","30<40","40<50","50<60","60<70","70<80","80<90",  
                                  "90<100","100<110","110<120","120<130","130<140","150<160"),
                          Freq=c(295, 120,  67, 114,  81, 101,  60,  25,  35,  16,   2,   5,   2,   3,   1, 516,
                                 184, 146, 170, 158, 161, 113,  79,  70,  20,   1,   2,   3,   4,   1, 471, 204,
                                 223, 142, 157, 182, 139, 133,  74,  44,   4,   5,  10,   2,   1,   1,   1,   1,
                                 379, 137, 173, 127, 112, 101,  85,  67,  27,  18,   3,   2,   3,   2))

ggplot(data,aes(x=cut, y=Freq))  
  geom_bar(stat = "identity", fill="#1B9E77",alpha=0.9) 
  theme(axis.text.x =  element_text(size = 12,angle = 90,vjust=0.5)) 
  facet_wrap(Group~.,scales = "free_x")
  

enter image description here

CodePudding user response:

unique(data$cut) would create the factor levels based on their occurrence in the data. You may try to create the factors as following -

library(ggplot2)
v1 <- seq(10, 300, 10)
data$cut <- factor(data$cut, paste(v1[-length(v1)], v1[-1], sep = '<'))

and now you can plot :

ggplot(data,aes(x=cut, y=Freq))  
  geom_bar(stat = "identity", fill="#1B9E77",alpha=0.9) 
  theme(axis.text.x =  element_text(size = 12,angle = 90,vjust=0.5)) 
  facet_wrap(Group~.,scales = "free_x")

enter image description here

  • Related