根据相关性计算标准误差,并作为误差线添加到条形图中

问题描述 投票:0回答:1

我想绘制数据集中几个因素之间的相关性。如果可能的话,我想尝试向这些绘制的值添加误差线或晶须。 mtcars的示例数据集虽然不是最大的,但它是可用的。实际数据沿x轴使用时间序列。我指定spearman是因为这是我的分析中使用的相关性,而不是因为它是mtcars数据集中的正确选择。我已经看到其他一些posts建议使用cor.test并从中提取值,但是我不确定如何将其应用于条形图以用作误差线。这是下面创建基本条形图的代码。

mtcarstest <- mtcars %>%
  group_by(cyl) %>%
  summarise(COR = cor(disp,hp, method = "spearman", use="complete.obs"))

ggplot(data = mtcarstest) +
  aes(x = cyl, y = COR) +
  geom_bar(stat = "identity") +
  theme_minimal()

enter image description here

r correlation errorbar standard-error
1个回答
0
投票

cor.test产生一个列表,其中实际上所有内容都存储了所需的内容。因此,只需编写一个获取所需值的函数即可。我们可以在此处使用by,这会产生一个列表,我们可以rbind获得具有完美行名的矩阵进行绘图。

res <- do.call(rbind, by(mtcars, mtcars$cyl, function(x) {
  rr <- with(x, cor.test(disp, hp, method="pearson"))
  return(c(rr$estimate, CI=rr$conf.int))
}))
# res
#          cor        CI1       CI2
# 4  0.4346051 -0.2235519 0.8205544
# 6 -0.5136284 -0.9133933 0.3904543
# 8  0.1182556 -0.4399266 0.6105282

注意,method="spearman"不适用于mtcars数据,因此我在这里使用了"pearson"

为了绘制数据,我建议使用R随附的barplot。我们存储钢筋位置b <-,并将其用作arrows的x坐标。对于y坐标,我们从矩阵中获取值。

b <- barplot(res[,1], ylim=range(res)*1.2, 
             main="My Plot", xlab="cyl", ylab="Cor. disp ~ hp")
arrows(b, res[,2], b, res[,3], code=3, angle=90, length=.1)
abline(h=0)
box()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.