使用 R 中的基本图形使用 SEM 误差条对条形图进行分组?

Grouped bar plots with SEM errorbars using base graphics in R?

编辑:根据下面的评论,我决定更加明确。所以这是我正在处理的数据的示例。

> example_data
   A     B        outcome
1  2.31  1.47       Y
2  2.14  1.32       N
3  3.49  1.00       Y
4  2.12  0.62       Y
5  0.47  0.55       N
6  3.36  0.50       N
7  3.50  0.33       Y
8  1.97  0.39       Y
9  3.12  0.99       N
10 2.04  0.89       Y
11 2.78  0.36       Y
12 1.83  0.70       N
13 3.53  0.77       N
14 2.25  0.39       N
15 1.67  0.43       N
16 3.09  1.10       Y

所以,我有两个变量 AB。它们是一个更大变量的子组,因此它们可以在同一个 y 轴上表示。我想用另一个有两个级别的变量 outcome 对它们进行分组。

我执行以下操作

> dataset <- example_data
> attach(dataset)
> means1<- tapply(A,outcome,function(x) mean(x,na.rm=TRUE))
> means2<- tapply(B,outcome,function(x) mean(x,na.rm=TRUE))
> std.err1<- tapply(A,outcome,function(x)sd(x,na.rm=TRUE)/sqrt(length(na.omit(x))))
> std.err2<- tapply(B,outcome,function(x)sd(x,na.rm=TRUE)/sqrt(length(na.omit(x))))
> matrix_means<- matrix(c(means1,means2),byrow = TRUE)
> graph<- barplot(matrix_means, beside=TRUE, space=c(0.2,0,0.2,0), axes=FALSE, ann=FALSE, col=c("white","black","red","blue"),ylim=c(0,4), names=c("Outcome-N","Outcome-Y","Outcome-N","Outcome-Y"), xpd=FALSE)
> axis(2, cex.axis=1.5)

现在我还需要使用箭头函数在每个组的平均值和 mean+sem 之间绘制 SEM 条。

我可以使用 tapply 获得 SEM,但不知道如何将箭头放置在 4 个栏中的每个栏上。

> arrows(graph, means1, graph, means1 + std.err1, graph, means2, graph, means2 + std.err2, code=3, angle=90, length=0.1)

这不会在图上放置任何箭头。

使用 base 图形而不是 ggplot2,我该怎么做?有人可以帮忙吗?我的所有其他图表都是使用 R 中的 GrapheR 包完成的,所以我也尝试使用基本图形来完成这个,这样它们在我的手稿中看起来都是一样的。

谢谢。

R.S。是正确的,如果您输入 MCVE,我们将更容易理解您的问题并了解如何提供帮助。如果您的数据集非常大并且很难为其创建合理的子集,则预加载的数据集可以派上用场。您可以通过 运行 data(package="datasets").

获取可用列表

在这种情况下,你的问题很笼统,从你写的内容来看,你已经完成了一半以上。 您创建的 graph 对象包含相关的 x 值。使用均值和 SEM 值,您已经知道箭头应该从哪里开始以及它们应该延伸多远,所以您所要做的就是将这些信息作为向量传递给 arrow 函数,然后您就成功了。

由于您没有提供任何数据,我将使用 mtcars 数据集进行演示。

data(mtcars)

summ.df <- data.frame(
  mean=tapply(mtcars$hp, mtcars$cyl, mean),
  sd=tapply(mtcars$hp, mtcars$cyl, sd),
  n=tapply(mtcars$hp, mtcars$cyl, length))

summ.df$sem <- summ.df$sd/sqrt(summ.df$n)

par(mar=c(2.5, 2.5, 2, 1.5))
bplt <- barplot(summ.df$mean, col="white")
arrows(bplt, summ.df$mean+summ.df$sem, 
       bplt, summ.df$mean-summ.df$sem, 
       angle=90, code=3, xpd=NA, length=0.1)

回复更新
arrows 的调用是给您带来麻烦的原因。如果您阅读文档 (?arrows),您会看到前四个参数是箭头起点和终点的 x 和 y 坐标。对于每个箭头,开始和结束 x 值相同(它们完全垂直)并由 graph 给出,而结束和开始 y 值分别由平均值 ± SEM 给出。

因此,您将通过调用

获得正确的结果
arrows(graph, c(means1, means2) + c(std.err1, std.err2), 
       graph, c(means1, means2) - c(std.err1, std.err2), 
       code=3, angle=90, length=0.1)