4

I'm trying to create a stacked bar graph with errorbars* using ggplot2, similar to the plot below: Plot I'm trying to replicate

I've used the following code:

df <- data.frame(substrate = gl(6, 2, 12, labels=letters[1:6]),
                 depth = gl(2, 1, 12, labels=c("surf", "deep")),
                 mean = 10 * runif(12),
                 err = runif(12))
p <- ggplot(df, aes(x=depth, y=mean, fill=substrate)) + geom_bar(stat="identity") + coord_flip()
p + geom_errorbar(aes(x=depth, ymin=mean-err, ymax=mean+err))

Which gives me this: enter image description here

It looks like the center of the errorbars at the position of mean instead of mean + the means of the "previous" substrates. That is, the center of errorbar a should be at the mean of a, the center of errorbar b should be at mean a + mean b, etc.

Does anyone know how to make this happen in ggplot2?

*I realize there are excellent theoretical reasons not to display data this way - but we don't always get to decide for ourselves how to present our data!

1 Answer 1

5

I suppose you could do this with geom_segment, but your example only has the bars going in one direction, which seems smarter. So I hacked something together with geom_segment:

df <- data.frame(substrate = gl(6, 2, 12, labels=letters[1:6]),
                 depth = gl(2, 1, 12, labels=c("surf", "deep")),
                 mean = 10 * runif(12),
                 err = runif(12))
df <- ddply(df,.(depth),transform,ystart = cumsum(mean),yend = cumsum(mean) + err)
p <- ggplot(df, aes(x=depth, y=mean, fill=substrate)) + 
        geom_bar(stat="identity")
p + geom_segment(aes(xend = depth,y = ystart,yend = yend)) + 
        geom_point(aes(x = depth,y = yend),shape = "|",show_guide = FALSE) +
        coord_flip()

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

The one-direction bars are much better - they reduce the chance of overlap between bars.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.