过滤堆积条形图中的 geom_text 值标签

fli*_*ech 5 r ggplot2

我想用 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))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

#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)) 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

akr*_*run 3

我们可以创建一个值小于或等于 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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


通过与 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"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述