叠加的条形码和标签错误的堆叠geom_bar问题

时间:2016-09-14 23:43:27

标签: r ggplot2 geom-bar

我有这个条形图:

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")

enter image description here

我希望堆积的条形图和显示的值。当我运行上面的代码时,-76不在正确的位置(似乎也不是75)。

知道如何让数字出现在正确的位置吗?

2 个答案:

答案 0 :(得分:1)

3.141592653589793

enter image description here

答案 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")

enter image description here

如果使用当前开发版本的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")