3

I'm using the ggplot R package, I did this plot with the code below:

p3 = data.frame(cbind(c(1:70),
                      c("G1" ,  "G2" ,  "G1" ,  "G1" ,  "G1" ,  "G2"  ,   "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1",  
                        "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G2" ,  "G1" ,  "G2"  ,   "G1" ,  "G1"  ,
                        "G1" ,  "G1" ,  "G1" ,  "G2" , "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1"  ,
                        "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" , 
                        "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G2" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G1" , 
                        "G1" ,  "G1" ,  "G1" ,  "G1" ,  "G2"),
                      c(rep("B",35),rep("C",15),rep("A",20))
))

colnames(p3)=c("Num","L" , "G")

library(ggthemes)
library(ggplot2)

pp <- ggplot(p3, aes(Num, G)) + 
  geom_tile(aes(fill = L), colour = "white") 
pp + theme(legend.position="bottom", axis.text.x  = element_text(angle=90, size=7,vjust=0.5)) + # scale_fill_grey() + theme_classic()
  scale_fill_manual(values=c("#990000","#E69F00","#999999"))

enter image description here

I would like to change the order of y-axis values according to the number of bars (= variable G)

The expected plot:

enter image description here

Thanks a lot for your helps !

Flora Grappelli
  • 659
  • 9
  • 26
Ph.D.Student
  • 704
  • 6
  • 27

2 Answers2

2

Change levels for p3$G according to sorted table of p3$G variable:

p3$G <- factor(p3$G, names(sort(table(p3$G))))

sort(table(p3$G))
# C  A  B 
# 15 20 35
pogibas
  • 27,303
  • 19
  • 84
  • 117
1

You can set how you want the G column of your dataframe to be ordered by setting it to type factor, and setting the levels. This can all be done with:

levels(p3$G) <- c("C", "A", "B")
C. Braun
  • 5,061
  • 19
  • 47