如何在 R 中的分组条形图上创建误差线?

时间:2021-05-11 06:02:18

标签: r ggplot2

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

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

enter image description here

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)

但我收到以下错误:

<块引用>

层中的错误(数据 = 数据,映射 = 映射,统计 = 统计,geom = GeomErrorbar,:未找到对象“std”

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

1 个答案:

答案 0 :(得分:0)

以下内容可能对您有用:

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 的值必须手动设置。

输出:

enter image description here