如何使用ggplot在堆叠和分组的条形图中显示值标签

How to show value label in stacked and grouped bar chart using ggplot

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

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

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

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

试试这个。可能诀窍是在 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 创建

您需要将数据和美学从 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)