Stacked barplot with errorbars using ggplot2

2019-05-09 12:54发布

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!

标签: r ggplot2
1条回答
走好不送
2楼-- · 2019-05-09 13:15

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

查看更多
登录 后发表回答