我的问题是关于如何使用ggplot在堆叠和分组的条形图中显示数据(或值)标签。该图表采用此处stacked bars within grouped bar chart已解决的形式。
用于生成图表的代码可以在上面链接的问题的第一个答案中找到。链接中的问题中也提供了示例数据集。为了显示值标签,我尝试使用
扩展该代码。+ geom_text(aes(label=value), position=position_dodge(width=0.9), vjust=-0.25)
但是这对我不起作用。我对此非常感谢。
尝试一下。可能的诀窍是在position_stack
中使用geom_text
。
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")
...和调整位置等。>