从数据帧向 geom_col 添加误差线

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

我正在尝试将误差线添加到以下数据框的图中:

Village <- as.factor(c("Beng-Gaty", "Beng-Gaty", "Ohchra", "Ohchra", "Ohtrone", "Ohtrone", "Sraevly", "Sraevly"))
Prevalence_Measure <- as.factor(c("Crude", "Adjusted", "Crude", "Adjusted", "Crude", "Adjusted", "Crude", "Adjusted"))
Prevalence <- as.numeric(c(37.7, 42.3, 39.5, 43.9, 19.4, 30, 18.2, 21.2))
Lower_CI <- as.numeric(c(0.285, 0.329, 0.316, 0.360, 0.123, 0.215, 0.124, 0.152))
Upper_CI <- as.numeric(c(0.476, 0.524, 0.477, 0.524, 0.283, 0.399, 0.252, 0.288))

Village_Prevalences_Comp <- data.frame(Village, Prevalence_Measure, Prevalence, Lower_CI, Upper_CI)

我已经尝试了以下两种方法并在网上查看 - 但它仍然让我感到困惑:

前两项努力没有“躲避”误差线,并且似乎只有一个误差线(在错误的位置),而应该有两个。

Village_Prevalences_Comp %>%
  ggplot() +
  geom_col( 
    mapping = aes(
      x=Village, 
      fill=Prevalence_Measure,
      y=Prevalence),
    position = "dodge") +
  geom_pointrange(aes(x=Village, y=Prevalence, ymin=Lower_CI, ymax=Upper_CI))
  
Village_Prevalences_Comp %>%
  ggplot(aes(x=Village, fill=Prevalence_Measure, y=Prevalence)) +
  geom_col(position = "dodge") +
  geom_line(ymin=Lower_CI, ymax=Upper_CI)

这里的第三个示例有两个误差线,但它们位于图表上的 y = 0 点。

Village_Prevalences_Comp %>%
  ggplot() +
  geom_col( 
    mapping = aes(
      x=Village, 
      fill=Prevalence_Measure,
      y=Prevalence),
    position = "dodge") +
  geom_errorbar(data = Village_Prevalences_Comp, aes(x=Village, ymin=Lower_CI, ymax=Upper_CI))

谢谢

geom-bar errorbar
1个回答
0
投票

在意识到我的愚蠢错误后,我打算删除我的问题,但后来想到可能还有像我一样的其他人犯了同样的愚蠢错误。

我意识到我的上置信区间和下置信区间都是以比例而不是百分比的形式给出的,所以当然误差线在 y=0 处被压缩。

以下代码现在可以运行了

Prevalence_Measure <- as.factor(c("Crude", "Adjusted", "Crude", "Adjusted", "Crude", "Adjusted", "Crude", "Adjusted"))
Prevalence <- as.numeric(c(37.7, 42.3, 39.5, 43.9, 19.4, 30, 18.2, 21.2))
Lower_CI <- as.numeric(c(28.5, 32.9, 31.6, 36.0, 12.3, 21.5, 12.4, 15.2))
Upper_CI <- as.numeric(c(47.6, 52.4, 47.7, 52.4, 28.3, 39.9, 25.2, 28.8))

Village_Prevalences_Comp <- data.frame(Village, Prevalence_Measure, Prevalence, Lower_CI, Upper_CI)

ggplot(Village_Prevalences_Comp, aes(x = Village, y = Prevalence, fill = Prevalence_Measure)) +
  geom_col(position = "dodge") +
  geom_errorbar(aes(ymin = Lower_CI, ymax = Upper_CI),
                position = position_dodge(width = 0.9), width = .2)
© www.soinside.com 2019 - 2024. All rights reserved.