[英]stacked geom_bar issue with stacked bar and labels misplaced
我有这个条形图:
group = c("A","A","B","B")
value = c(25,-75,-40,-76)
day = c(1,2,1,2)
dat = data.frame(group = group , value = value, day = day)
ggplot(data = dat, aes(x = group, y = value, fill = factor(day))) +
geom_bar(stat = "identity", position = "identity")+
geom_text(aes(label = round(value,0)), color = "black", position = "stack")
我希望条形堆叠并显示值。 当我运行上面的代码时,-76 不在正确的位置(看起来 75 也不是)。
知道如何让数字出现在正确的位置吗?
对于 ggplot2 来说,堆叠负值和正值的混合是很困难的。 最简单的做法是将数据集一分为二,一为正数,一为负数,然后分别添加条形层。 一个经典的例子在这里。
您可以对文本执行相同的操作,为正 y 值添加一个文本层,为负值添加一个文本层。
dat1 = subset(dat, value >= 0)
dat2 = subset(dat, value < 0)
ggplot(mapping = aes(x = group, y = value, fill = factor(day))) +
geom_bar(data = dat1, stat = "identity", position = "stack")+
geom_bar(data = dat2, stat = "identity", position = "stack") +
geom_text(data = dat1, aes(label = round(value,0)), color = "black", position = "stack") +
geom_text(data = dat2, aes(label = round(value,0)), color = "black", position = "stack")
如果使用当前开发版本的 ggplot2 (2.1.0.9000),则在geom_text
对于负值的堆叠似乎无法正常工作。 如果需要,您始终可以“手动”计算文本位置。
library(dplyr)
dat2 = dat2 %>%
group_by(group) %>%
mutate(pos = cumsum(value))
ggplot(mapping = aes(x = group, y = value, fill = factor(day))) +
geom_bar(data = dat1, stat = "identity", position = "stack")+
geom_bar(data = dat2, stat = "identity", position = "stack") +
geom_text(data = dat1, aes(label = round(value,0)), color = "black") +
geom_text(data = dat2, aes(label = round(value,0), y = pos), color = "black")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.