r - 使用 ggplot2 带有误差条的堆叠条形图

标签 r ggplot2

我正在尝试使用 ggplot2 创建一个带有 errorbars* 的堆积条形图,类似于下图:
Plot I'm trying to replicate

我使用了以下代码:

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

这给了我这个:
enter image description here

它看起来像是位于均值位置的误差条的中心,而不是均值 + “先前”基板的均值。也就是说,误差条 a 的中心应该在 a 的平均值处,误差条 b 的中心应该在平均值 a + 平均值 b 处,依此类推。

有谁知道如何在 ggplot2 中做到这一点?

*我意识到不以这种方式显示数据有很好的理论理由 - 但我们并不总是能够自己决定如何呈现我们的数据!

最佳答案

我想你可以用 geom_segment 做到这一点,但你的例子只有一个方向的酒吧,这似乎更聪明。所以我和 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

关于r - 使用 ggplot2 带有误差条的堆叠条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10417003/

相关文章:

具有范围(或聚合)的 R group_by

r - 如何在纬度和经度上从 R 中的 PostGis 转换 Geom 对象?

R读取具有时间戳的CSV文件

r - ggsignif 包错误 stat_signif 需要以下缺失的美观 : y

r - ggplot geom_bar:aes(组= 1)的含义

r - 如何找到两个值的组合,使它们的比率和总和固定为 R 的某些数字

r - 在 r 中从宽到长的复杂 reshape

r - 没有标题的 ggplot 图例为标题留出空间

R.ggplot2。如何更改 2 条线的颜色,以便在 2-y 轴图上区分它们

在生成箱线图时提醒 R 整数是一个因素