我有这个条形图:
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)。
知道如何让数字出现在正确的位置吗?
答案 0 :(得分:1)
答案 1 :(得分:0)
ggplot2很难堆叠负值和正值的混合。最简单的方法是将数据集拆分为两个,一个用于正数,一个用于负数,然后分别添加条形图层。一个典型的例子是here。
您可以对文本执行相同操作,为正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")