【问题标题】:stack bars in plot without preserving label order在不保留标签顺序的情况下堆叠条形图
【发布时间】:2020-08-30 05:40:46
【问题描述】:

ggplot 根据标签保留堆叠条的顺序:

d <- read.table(text='Day Location Length Amount
            1 2 3 1
            1 1 4 2
            3 3 3 2
            3 2 5 1',header=T)

d$Amount<-as.factor(d$Amount) # in real world is not numeric

ggplot(d, aes(x = Day, y = Length)) + 
  geom_bar(aes(fill = Amount), stat = "identity")

我想要的是与没有as.factor 线的情节类似的结果。那就是:更大的条总是在顶部。但是,我不能对我的数据执行此操作,因为我有类别,而不是数字。

类似帖子:https://www.researchgate.net/post/R_ggplot2_Reorder_stacked_plot

解决方案可以来自其他 R 包

注意:data.frame 只是示范性的。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我想出了这个解决方案:

    (1)首先对data.frame按列值进行降序排序

    (2) 然后复制一列值,作为因子。

    (3) 在 ggplot 组中按新因子(值)

    d <- read.table(text='Day Length Amount
                    1 3 1
                    1 4 2
                    3 3 2
                    3 5 1',header=T)
    
    d$Amount<-as.factor(d$Amount) 
    
    d <- d[order(d$Length, decreasing = TRUE),] # (1)
    
    d$LengthFactor<-factor(d$Length, levels= unique(d$Length) ) # (2)
    
    ggplot(d)+
      geom_bar(aes(x=Day, y=Length, group=LengthFactor, fill=Amount), # (3)
               stat="identity", color="white") 
    

    {
    library(data.table)
    sam<-data.frame(population=c(rep("PRO",8),rep("SOM",4)),
                    allele=c("alele1","alele2","alele3","alele4",rep("alele5",2),
                                rep("alele3",2),"alele2","alele3","alele3","alele2"), 
                    frequency=rep(c(10,5,4,6,7,16),2) #,rep(1,6)))
    )
    
    sam <- setDT(sam)[, .(frequencySum=sum(frequency)), by=.(population,allele)]
    
    sam <- sam[order(sam$frequency, decreasing = TRUE),] # (1)
    
    # (2)
    sam$frequency<-factor(sam$frequency, levels = unique(sam$frequency) )
    
    library(ggplot2)
    ggplot(sam)+
      geom_bar(aes(x=population, y=frequencySum, group=frequency, fill=allele), # (3)
               stat="identity", color="white") 
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      相关资源
      最近更新 更多