【问题标题】:How to show value label in stacked and grouped bar chart using ggplot如何使用ggplot在堆叠和分组条形图中显示值标签
【发布时间】:2020-06-05 07:47:57
【问题描述】:

我的问题是关于如何使用 ggplot 在堆叠和分组的条形图中显示数据(或值)标签。该图表的形式是此处已解决的问题stacked bars within grouped bar chart

生成图表的代码可以在上述链接中问题的第一个答案中找到。链接中的问题还给出了一个示例数据集。为了显示值标签,我尝试使用

扩展该代码
+ geom_text(aes(label=value), position=position_dodge(width=0.9), vjust=-0.25)

但这对我不起作用。我非常感谢这方面的任何帮助。

【问题讨论】:

    标签: r ggplot2 plot bar-chart stacked-chart


    【解决方案1】:

    您需要将数据和美学从geom_bar() 移动到ggplot(),以便geom_text() 可以使用它。

    ggplot(data=test, aes(y = value, x = cat, fill = cond)) +
        geom_bar(stat = "identity", position = "stack") +
        theme_bw() + 
        facet_grid( ~ year) +
        geom_text(aes(label = value), position = "stack")
    

    然后您可以使用标签,例如省略零:

    ggplot(data=test, aes(y = value, x = cat, fill = cond)) +
        geom_bar(stat = "identity", position = "stack") +
        theme_bw() + 
        facet_grid( ~ year) +
        geom_text(aes(label = ifelse(value != 0, value, "")), position = "stack")
    

    ...并通过vjust调整位置:

    ggplot(data=test, aes(y = value, x = cat, fill = cond)) +
        geom_bar(stat = "identity", position = "stack") +
        theme_bw() + 
        facet_grid( ~ year) +
        geom_text(aes(label = ifelse(value != 0, value, "")), position = "stack", vjust = -0.3)
    

    【讨论】:

      【解决方案2】:

      试试这个。可能诀窍是在geom_text 中使用position_stack

      library(tidyverse)
      
      test <- expand.grid('cat' = LETTERS[1:5], 'cond'= c(F,T), 'year' = 2001:2005)
      test$value <- floor((rnorm(nrow(test)))*100)
      test$value[test$value < 0] <- 0
      
      ggplot(test, aes(y = value, x = cat, fill = cond)) +
        geom_bar(stat="identity", position='stack') +
        geom_text(aes(label = ifelse(value > 0, value, "")), position = position_stack(), vjust=-0.25) +
        theme_bw() + 
        facet_grid( ~ year)
      

      reprex package (v0.3.0) 于 2020-06-05 创建

      【讨论】:

        猜你喜欢
        • 2021-11-16
        • 2018-03-17
        • 2018-04-01
        • 1970-01-01
        • 2021-07-01
        • 1970-01-01
        • 2019-03-14
        • 2014-08-24
        • 2020-10-05
        相关资源
        最近更新 更多