首页 > 解决方案 > 如何在 R 中的分组条形图上创建误差线?

问题描述

我正在查看一篇论文的一些数据,我需要创建一个图表来显示 2 个不同时期(之前和期间)焦虑/抑郁的平均得分差异。我也被指示在图表中插入标准误差线。

当我尝试不带误差线的图表时,我使用 ggplot2 并使用以下代码行获取此条形图:

在此处输入图像描述

library(ggplot2)

mh1 <- read.table(
  header=TRUE, text='Category        mean Period  std
1   Depression      0.720      Pre  1.03
2   Depression      0.779      During 0.78
3   Anxiety         0.996      Pre  1.27
4   Anxiety           0.977      During 1.14')


mh1$s <- as.character()
ggplot(mh1, aes(Category, mean, fill = Period)) +
  geom_bar(stat = "identity", position = "dodge") +
  scale_fill_brewer(palette = "Set1") +
  xlab("") +
  ylab("Mean Score") +
  ylim(0, 3)

对于误差线,我使用“+”运算符将以下函数附加到上面的函数

geom_errorbar(Category, ymin = mean - std, ymax = mean + std)

但我收到以下错误:

图层错误(数据 = 数据,映射 = 映射,stat = stat,geom = GeomErrorbar,:找不到对象“std”

我对自己做错了什么有点困惑,希望得到一些帮助!

标签: rggplot2

解决方案


以下是您可能会发现有用的内容:

library(ggplot2)
ggplot(mh1, aes(Category, mean, fill = Period)) +
  geom_bar(stat = "identity", position = position_dodge(width = 1)) +
  geom_errorbar(aes(ymin = mean - std, ymax = mean + std), 
                position = position_dodge(width = 1))

的值width = 1必须手动设置。

输出:

在此处输入图像描述


推荐阅读