1

I have this bar chart:

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

and I'd like the bars stacked and the values to show up. When I run the code above the -76 is not in the correct location (and neither is the 75 it seems).

Any idea how to get the numbers to appear in the correct location?

J. Chomel
  • 8,193
  • 15
  • 41
  • 69
user3022875
  • 8,598
  • 26
  • 103
  • 167

2 Answers2

1
ggplot(data=dat, aes(x=group, y=value, fill=factor(day))) +
    geom_bar(stat="identity", position="identity")+
    geom_text(label =round(value,0),color = "black")+
    scale_y_continuous(breaks=c(-80,-40,0))

enter image description here

Cyrus Mohammadian
  • 4,982
  • 6
  • 33
  • 62
  • 1
    OP would "like the bars stacked". If you disagree, you should at least explain that in the answer. – Axeman Sep 15 '16 at 07:25
0

Stacking a mix of negative and positive values is difficult for ggplot2. The easiest thing to do is to split the dataset into two, one for positives and one for negatives, and then add bar layers separately. A classic example is here.

You can do the same thing with the text, adding one text layer for the positive y values and one for the negatives.

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

If using the currently development version of ggplot2 (2.1.0.9000), the stacking doesn't seem to be working correctly in geom_text for negative values. You can always calculate the text positions "by hand" if you need to.

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")
Community
  • 1
  • 1
aosmith
  • 34,856
  • 9
  • 84
  • 118