改变y轴值的顺序

时间:2022-10-19 09:39:51

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

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

改变y轴值的顺序

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

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

The plot expected :

故事情节:

改变y轴值的顺序

2 个解决方案

#1


2  

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

根据p3$G变量的排序表,p3$G的变化水平:

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

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

#2


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:

您可以通过将dataframe的G列设置为factor并设置级别来设置它的排序方式。这一切都可以做到:

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

#1


2  

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

根据p3$G变量的排序表,p3$G的变化水平:

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

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

#2


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:

您可以通过将dataframe的G列设置为factor并设置级别来设置它的排序方式。这一切都可以做到:

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