I am trying to plot different points, some of which are observations (therefore with no error bars), others are predictions (with error bars). I used position_dodge to place my points, but because there are missing values for error bars, I cannot find a way to match the error bars with their respective points.
Below I tried to make a simple reproducible example inspired from my dataset.
a <- data.frame(taxon = "plants", type = c(rep("observation", 3), "prediction"), period = c("1970-2017", "2000-2009", "2010-2017", "2017"), value = 1:4, lwr = c(NA, NA, NA, 3.5), upr = c(NA, NA, NA, 4.5))
a
#> taxon type period value lwr upr
#> 1 plants observation 1970-2017 1 NA NA
#> 2 plants observation 2000-2009 2 NA NA
#> 3 plants observation 2010-2017 3 NA NA
#> 4 plants prediction 2017 4 3.5 4.5
This is the code I used for ggplot:
ggplot(a) +
geom_point(aes(x = taxon,
shape = type,
y = value,
col = period),
position = position_dodge(width = .5)) +
geom_errorbar(aes(x = taxon,
ymin = lwr, ymax = upr),
position = position_dodge(width = .5))
As you can see, the error bar is centered, most likely because the missing values in lwr
and upr
have been omitted, whereas it should be on the top right point.
All my attempts to fix this (i.e., different settings with position_dodge
, try to specify the preserve
argument) have been unsuccessful so far, and I have not been able to find help on internet.