【问题标题】:Filter geom_text value labels in a stacked bar chart在堆积条形图中过滤 geom_text 值标签
【发布时间】:2018-01-10 11:52:03
【问题描述】:

我想用 ggplot 创建一个堆积条形图,并为其添加(居中)标签:当值太低时,我不想显示标签。

df<-data.frame(x=unlist(strsplit("AAAABBBB","")),
           z=unlist(strsplit("ABCDABCD","")),
           y=c(40,5,30,10,50,60,5, 40))

# this works fine
library(ggplot2)
ggplot(df, aes(x=x, y=y, fill = z)) + geom_bar(stat="identity") + 
   geom_text(data  = df, aes(x=x, y=y, label = y), position = position_stack(vjust=0.5))

但是当我像这样过滤值时(见下文),它也会改变每个标签的位置。这适用于散点图,但由于定位基于堆叠值,因此标签显示得太低。

#don't show values 5 or less
ggplot(df, aes(x=x, y=y, fill = z)) + geom_bar(stat="identity") + 
    geom_text(data = df[df$y > 5,], aes(x=x, y=y, label = y), position = 
    position_stack(vjust=0.5)) 

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我们可以创建一个值小于或等于 5 的列 'y1' 作为空白 ("") 并在 label 参数中使用它

    df %>% 
         mutate(y1 = replace(y, y<=5, ""))
    
    p2 <- ggplot(df, aes(x=x, y=y, fill = z)) + 
             geom_bar(stat="identity") + 
             geom_text(data  = df, aes(x=x, y=y, label = y1),
                      position = position_stack(vjust=0.5))
    p2
    


    通过与 OP 帖子中的第一个图进行比较来检查位置

    p1 <- ggplot(df, aes(x=x, y=y, fill = z)) + 
                      geom_bar(stat="identity") +
                      geom_text(data  = df, aes(x=x, y=y, label = y), 
                          position = position_stack(vjust=0.5))
    
    library(ggpubr)
    ggarrange(p1, p2, ncol =2, nrow = 1, labels = c("p1", "p2"))
    

    【讨论】:

    • 感谢您指出这一点。有一些我不知道的奇怪问题,稍后会尝试解决它。您的解决方案非常好,但是我不会创建新列,而是会这样做:aes(label = ifelse(y &gt; 5, y, ""))
    • @PoGibas 我想就是这样。我看到你在做类似的事情,所以没有改变它