更改y轴值的顺序

时间:2018-04-12 13:05:47

标签: r plot ggplot2 axes

我使用R中的 ggplot 包,我用这段代码做了这个情节:

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

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

预期的情节:

enter image description here

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

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

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