使用ggplot2与错误条堆叠的barplot [英] Stacked barplot with errorbars using ggplot2

查看:120
本文介绍了使用ggplot2与错误条堆叠的barplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用ggplot2创建一个带有错误条*的堆积条形图,类似于下图:



我使用了下面的代码:

<$ p (基底= gl(6,2,12,标签=字母[1:6]),
depth = gl(2,1,12 ,标签= 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))

这给了我:

它看起来像位于均值位置的误差线的中心而不是平均值+先前底物的手段。也就是说,错误栏a的中心应该是a的平均值,错误栏b的中心应该位于平均值a +平均值b等处。

有谁知道如何在ggplot2中实现这一点?



*我意识到有理想的理由不以这种方式显示数据 - 但我们并不总是自己决定如何来展示我们的数据!

解决方案

我想你可以用 geom_segment ,但你的例子只有一个方向的酒吧,这似乎更聪明。所以我用 geom_segment 来破解一些东西:

  df < - 数据(底部= gl(6,2,12,标签=字母[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()


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

这篇关于使用ggplot2与错误条堆叠的barplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆