【问题标题】:Position geom_text in the middle of each bar segment in a geom_col stacked barchart [duplicate]将geom_text放置在geom_col堆叠条形图中每个条形段的中间[重复]
【发布时间】:2017-04-05 01:58:52
【问题描述】:

我想将相应的值标签放置在每个条形段中间的geom_col 堆叠条形图中

但是,我天真的尝试失败了。

library(ggplot2) # Version: ggplot2 2.2

dta <- data.frame(group  = c("A","A","A",
                             "B","B","B"),
                  sector = c("x","y","z",
                             "x","y","z"),
                  value  = c(10,20,70,
                             30,20,50))

ggplot(data = dta) +
  geom_col(aes(x = group, y = value, fill = sector)) +
  geom_text(position="stack",
            aes(x = group, y = value, label = value)) 

显然,将y=value/2 设置为geom_text 也无济于事。此外,文本的位置顺序错误(颠倒了)。

任何(优雅的)想法如何解决这个问题?

【问题讨论】:

    标签: r ggplot2 stacked-chart geom-text


    【解决方案1】:

    您需要将变量映射到美学以表示geom_text 中的组。对你来说,这是你的“部门”变量。您可以将其与geom_text 中的group 美学结合使用。

    然后使用position_stackvjust 使标签居中。

    ggplot(data = dta) +
        geom_col(aes(x = group, y = value, fill = sector)) +
        geom_text(aes(x = group, y = value, label = value, group = sector),
                      position = position_stack(vjust = .5))
    

    您可以通过全局设置美学来节省一些打字。然后fill 将用作geom_text 的分组变量,您可以跳过group

    ggplot(data = dta, aes(x = group, y = value, fill = sector)) +
        geom_col() +
        geom_text(aes(label = value),
                  position = position_stack(vjust = .5))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-31
      相关资源
      最近更新 更多