ggplot 堆叠条 - 隐藏标签但保留标签定位

cam*_*tor 2 r data-visualization ggplot2

我在 ggplot 中有一个堆叠条形图,geom_text() 标签位于每个条形的中心。我想隐藏小条上的标签,以便图表看起来不会过于拥挤。我可以使用下面的代码来做到这一点,但是正如您在下面的链接图片中看到的那样,它弄乱了标签的位置(它们不再居中)。

有没有办法隐藏条形图标签而不会弄乱剩余标签的位置?

ggplot(data=outcome,
      aes(x = category, y=percent,fill = outcome)) +
geom_bar(stat='identity') +
coord_flip() +
geom_text(data=outcome %>% filter(percent>=0.1),aes(label = percent), size = 3,position = position_stack(vjust = 0.5),
          check_overlap=TRUE) 
Run Code Online (Sandbox Code Playgroud)

带有错位标签的堆积条形图

aos*_*ith 5

您可以使用ifelse()语句。每次我不想要标签时,我都会在这里放空白,但NA也有效。

library(ggplot2)

df = data.frame(
     x = factor(c(1, 1, 2, 2)),
     y = c(1, 3, 2, 1),
     grp = c("a", "b", "a", "b")
)

ggplot(data = df, aes(x, y, fill = grp)) +
     geom_col() +
     coord_flip() +
     geom_text(aes(label = ifelse(y > 1, y, "")), 
               position = position_stack(vjust = 0.5),
               size = 3)
Run Code Online (Sandbox Code Playgroud)

reprex 包(v0.2.0)于 2018 年 8 月 7 日创建。