代码之家  ›  专栏  ›  技术社区  ›  Omry Atia

调整ggplot中误差条上方的文本位置

  •  1
  • Omry Atia  · 技术社区  · 6 年前

    我有以下数据框:

    df <- structure(list(Gender = c("M", "M", "M", "M", "F", "F", "F", 
    "F"), HGGroup = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = 
    c("Low: \n F: <11.5, M: <12.5", 
    "Medium: \n F: > 11.5 & < 13, M: >12.5 & < 14.5", "High: \n F: >= 13, M >= 
    14.5", "No data"), class = "factor"), MeanBlood = c(0.240740740740741, 
    1.20689655172414, 0.38150289017341, 0.265957446808511, 0.272727272727273, 
    1.07821229050279, 0.257309941520468, 0.288776796973518), SEBlood = 
    c(0.0694516553311722, 0.154646785911315, 0.0687932999815165, 
    0.0383529942166715, 0.0406072582435844, 0.0971802933392401, 
    0.0327856332532931, 0.0289636037703526), 
    N = c(108L, 116L, 173L, 376L, 319L, 179L, 342L, 793L)), row.names = c(NA, 
    -8L), class = c("tbl_df", "tbl", "data.frame"))
    

    我有以下命令来绘制每组的平均值和置信区间:

    ggplot(df, aes(x = Gender, y = MeanBlood, colour = Gender)) + 
    geom_errorbar(aes(ymin = MeanBlood - SEBlood*qnorm(0.975), ymax = MeanBlood 
    + SEBlood*qnorm(0.975)), width = 0.3, stat = "identity") +
    geom_point(size = 3) + facet_grid(~HGGroup) + theme(legend.position = 
    "none") + 
    geom_text(aes(label = N, x = Gender), vjust = -5)
    

    我正试图将文本准确地放在错误栏的顶部,但是每个组的文本都需要在不同的位置,而且现在看起来很奇怪。

    我认为这个问题源于这样一个事实,即每个组的置信区间长度不同,所以一个不变的理由是行不通的——它必须相对于下四分位数。

    有什么建议吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   moodymudskipper    6 年前

    这似乎奏效了, y 你的标签,你想要的,不是 Y 设置在 aes 属于 ggplot 但是 ymax :

    ggplot(df, aes(x = Gender, y = MeanBlood, colour = Gender)) + 
      geom_errorbar(aes(ymin = MeanBlood - SEBlood*qnorm(0.975), ymax = MeanBlood 
                        + SEBlood*qnorm(0.975)), width = 0.3, stat = "identity") +
      geom_point(size = 3) + facet_grid(~HGGroup) + theme(legend.position = 
                                                            "none") + 
      geom_text(aes(y = MeanBlood + SEBlood*qnorm(0.975), label = N, x = Gender), vjust = -1)
    

    如果你把Ymax搬到 格格图 调用其他层将能够访问它,因此无需重新定义它:

    ggplot(df, aes(x = Gender, y = MeanBlood, colour = Gender, 
                   ymin = MeanBlood - SEBlood*qnorm(0.975), ymax = MeanBlood 
                   + SEBlood*qnorm(0.975))) + 
      geom_errorbar(aes(width = 0.3), stat = "identity") +
      geom_point(size = 3) + facet_grid(~HGGroup) + theme(legend.position = 
                                                            "none") + 
      geom_text(aes(y = stat(ymax), label = N, x = Gender), vjust = -1)