R语言 在ggplot2中添加误差条会产生重叠条

zy1mlcev  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(276)

我有下面的数据表msumNZ

msumNZ <-  data.frame(
      Habitat = c(rep("Core", 6), rep("Wild", 6)),
      Parameter = rep(c("AlertForaging", "Foraging", "NA_OutOfSight ", 
                        "Other", "Social", "Vigilance"),2),
      mCounts = c(4.23, 5.74, 3.48, 4.93, 2.65, 4.31,
                  3.68, 5.9,  3.94, 3.82, 2.94, 4.83), 
      sd = c(3.63, 3.41, 2.73, 3.82, 1.93, 3.15, 
             1.93, 3.23, 3.32, 3.67, 2.15, 3.24))

我用ggplot绘制了一个条形图:

ggplot(mdta.summary.NZ, aes(x = Parameter, y = mCounts, fill = Habitat)) +
  geom_bar(stat = "identity", position = position_dodge())

这给出了以下图表:

现在,我想根据sd变量添加误差线,我将其添加到上面的代码中:

+ geom_errorbar(aes(ymin = mCounts, ymax = mCounts + sd, width = 0.2))

然而,我没有得到每个x参数的误差线,而是看起来两者重叠。

我做错了什么?

5gfr0r5j

5gfr0r5j1#

首先,您需要将误差条的position设置为position_dodge(),就像geom_bar()一样,沿着宽度来调整误差条的位置。
其次,ymin需要设置为mCounts-sd,就像ymax(mCounts + sd)一样,

library(ggplot2)
msumNZ <-  data.frame(
  Habitat = c(rep("Core", 6), rep("Wild", 6)),
  Parameter = rep(c("AlertForaging", "Foraging", "NA_OutOfSight ", 
                    "Other", "Social", "Vigilance"),2),
  mCounts = c(4.23, 5.74, 3.48, 4.93, 2.65, 4.31,
              3.68, 5.9,  3.94, 3.82, 2.94, 4.83), 
  sd = c(3.63, 3.41, 2.73, 3.82, 1.93, 3.15, 
         1.93, 3.23, 3.32, 3.67, 2.15, 3.24))

ggplot(msumNZ, aes(x = Parameter, y = mCounts, fill = Habitat)) +
  geom_bar(stat = "identity", position = position_dodge()) +
  geom_errorbar(aes(ymin = mCounts-sd, ymax = mCounts + sd, width = 0.2),
                position = position_dodge(width = .9))

创建于2023-04-30使用reprex v2.0.2

相关问题