将误差条添加到条形图

Add error bars to a barplot

我有两个向量。我想制作第一个向量的条形图(足够简单,对)。不同之处在于,第二个向量的每个元素都是第一个向量每个元素的标准差(它本身是其他 4 个值的平均值)。我该怎么做?

有问题的向量:

-4.6521175 0.145839723
 1.1744100 0.342278694
-0.2581400 0.003776341
-0.3452675 0.073241199
-2.3823650 0.095008502
 0.5625125 0.021627196

即,如何将第二个列向量的元素作为误差条添加到第一个列向量中的相应元素?

注意:在你问之前,是的,我确实在这个网站上进行了广泛的搜索并进行了大量的谷歌搜索,但我的问题更具体一些,即我发现的没有'符合我的需要。

geom_bargeom_errorbarggplot2 的实现:

library(ggplot2)
ggplot(df, aes(x=row.names(df), y=V1)) +
  geom_bar(stat="identity", fill="grey") +
  geom_errorbar(aes(ymin = V1 - V2, ymax = V1 + V2), width=0.6) +
  theme_classic() 

这导致:

如果要去掉x轴上的数字,可以加上:

  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

到你的 ggplot 代码。


已用数据:

df <- read.table(text="-4.6521175 0.145839723
 1.1744100 0.342278694
-0.2581400 0.003776341
-0.3452675 0.073241199
-2.3823650 0.095008502
 0.5625125 0.021627196", header=FALSE)

响应 ,当您想要绘制如此大量的柱形图时,有两种可能的解决方案:

1: 仅包括轴标签的选择:

ggplot(df2, aes(x=as.numeric(row.names(df2)), y=V1)) +
  geom_bar(stat="identity", fill="grey", width=0.7) +
  geom_errorbar(aes(ymin = V1 - V2, ymax = V1 + V2), width=0.5) +
  scale_x_continuous(breaks=c(1,seq(10,200,10)), expand=c(0,0)) +
  theme_classic() +
  theme(axis.text.x=element_text(size = 6, angle = 90, vjust = 0.5))

这给出:

可以看出,在一个图中塞满这么多条是不理想的。因此请参阅备选方案 2。

2: 创建一个可用于创建构面的分组变量:

df2$id <- rep(letters[1:20], each=10)

ggplot(df2, aes(x=as.numeric(row.names(df2)), y=V1)) +
  geom_bar(stat="identity", fill="grey", width=0.7) +
  geom_errorbar(aes(ymin = V1 - V2, ymax = V1 + V2), width=0.5) +
  scale_x_continuous(breaks=as.numeric(row.names(df2))) +
  facet_wrap(~ id, scales = "free_x") +
  theme_bw() +
  theme(axis.text.x=element_text(angle = 90, vjust = 0.5))

这给出:

最后两个示例使用的数据:

df2 <- data.frame(V1=sample(df$V1, 200, replace=TRUE),
                  V2=sample(df$V2, 200, replace=TRUE))

我个人最喜欢arrows()这种图形:

df <- data.frame(bar = c(-4.6521175, 1.1744100, -0.2581400,  -0.3452675, -2.3823650, 0.5625125),
error = c(0.145839723, 0.342278694, 0.003776341, 0.073241199, 0.095008502, 0.021627196))

foo <- barplot(df$bar,ylim=c(-6,2),border=NA)
arrows(x0=foo,y0=df$bar+df$error,y1=df$bar-df$error,angle=90,code=3,length=0.1)

两个细节:

  1. border=NA in barplot() 删除了条形图周围的边框,因此您实际上可以看到第三个条形图周围的错误胡须。由于第三个错误很小,胡须几乎位于条形边框的顶部。

  2. 我在 arrows() 中使用了 length 参数来减小水平胡须的宽度,如果我们有更多的条形图,这尤其重要。默认为 length=0.25.

但是,请注意"dynamite plots" have major disadvantages。您写道,您的数据仅来自每个条形图的四个原始点。在这种情况下,几乎 肯定 最好只绘制原始数据的(抖动的)点图。