简体   繁体   中英

Stacked barplot with errorbars using ggplot2

I'm trying to create a stacked bar graph with errorbars* using ggplot2, similar to the plot below: 情节我试图复制

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: 在此输入图像描述

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!

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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM