更改 y 轴值的顺序

Change the order of the y-axis values

我正在使用 ggplot R 包,我用下面的代码做了这个图:

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"))

我想根据柱数更改 y 轴值的顺序(= 变量 G)

预期剧情:

非常感谢您的帮助!

您可以设置数据框 G 列的排序方式,方法是将其设置为类型因子并设置级别。这一切都可以通过以下方式完成:

levels(p3$G) <- c("C", "A", "B")

根据 p3$G 变量的排序 table 更改 p3$G 的级别:

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

sort(table(p3$G))
# C  A  B 
# 15 20 35