代码之家  ›  专栏  ›  技术社区  ›  Jack Armstrong

ggplot2中带堆叠条形图的文本标签

  •  0
  • Jack Armstrong  · 技术社区  · 5 年前

    我正在尝试用文本标签制作堆叠条形图,下面是一些示例数据/代码:

    library(reshape2)
    
    ConstitutiveHet <- c(7,13)
    Enhancer <- c(12,6)
    FacultativeHet <- c(25,39)
    LowConfidence <- c(3,4)
    Promoter <- c(5,4)
    Quiescent <- c(69,59)
    RegPermissive <- c(23,18)
    Transcribed <- c(12,11)
    Bivalent <- c(6,22)
    group <- c("all","GWS")
    
    meanComb <- data.frame(ConstitutiveHet,Enhancer,LowConfidence,Promoter,Quiescent,RegPermissive,Transcribed,Bivalent,group)
    meanCombM <- melt(meanComb,id.vars = "group")
    
    ggplot(meanCombM,aes(group,value,label=value)) +
         geom_col(aes(fill=variable))+
         geom_text(position = "stack")+
         coord_flip()
    

    文本标签看起来不正常,它们似乎是它们预期顺序的镜像。(无论是否使用 coord_flip() )

    一张海报也有类似的问题: ggplot2: add ordered category labels to stacked bar chart

    他们的帖子给出了一个答案,我试着颠倒了组中值的顺序(见下文),结果图上的顺序不是我能弄清楚的。另外,这种方法似乎有问题,这里有一个bug还是我遗漏了什么?

    x <- c(rev(meanCombM[meanCombM$group=="GWS",]$value),rev(meanCombM[meanCombM$group=="all",]$value))
    
    ggplot(meanCombM,aes(group,value,label=x)) +
    geom_col(aes(fill=variable))+
    geom_text(position = "stack")+
    coord_flip()
    
    0 回复  |  直到 7 年前
        1
  •  6
  •   Richard J. Acton    7 年前
    ggplot(meanCombM,aes(group,value,label=value)) +
         geom_col(aes(fill=variable))+
         geom_text(aes(group=variable),position = position_stack(vjust = 0.5))+
         coord_flip()
    

    Hadley在ggplot2的git存储库中回答了一个类似于我自己的问题: https://github.com/tidyverse/ggplot2/issues/1972

    显然是默认的分组行为(参见: http://ggplot2.tidyverse.org/reference/aes_group_order.html )如果不指定 group 美学,应该映射到与 fill 在里面 geom_col 在这个例子中。