Search code examples
rggplot2geom-bar

adjusting position of text above an error bar in ggplot


I have the following data frame:

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"))

I have the following command for plotting the means and confidence intervals for each group:

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)

I am trying to get the text exactly on top of the error bar, but it needs to be in a different location for each group and currently comes out weird.

I think the problem originates from the fact that the confidence interval has a different length for each group, so that a constant justification would not work - it has to be relative to the lower quartile.

Any suggestions?


Solution

  • This seems to work, the y of your label, as you want it, is not the y set in the aes of ggplot, but is 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)
    

    If you move ymax to the ggplot call other layers will be able to access it so no need to redefine it:

    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)