【问题标题】:ggplot stacked bar - hide labels but preserve label positioningggplot 堆叠条 - 隐藏标签但保留标签定位
【发布时间】:2018-08-07 20:22:41
【问题描述】:

我在 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) 

【问题讨论】:

  • 我会使用 ifelse() 语句而不是过滤,将小值设置为 NA:label = ifelse(percent >= 0.1, percent, NA)

标签: r ggplot2 data-visualization


【解决方案1】:

您可以使用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)

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

【讨论】:

    猜你喜欢
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    相关资源
    最近更新 更多