rggplot2geom-point

How to order geom's that overlap within a fill/color? Adding jitter looks too random


Let's say I have this plot illustrating some odds ratio from a main analysis:

enter image description here

Unfortunately, the geom's are overlapping and it is difficult to see the full range of the confidence interval.

ggplot(df, aes(x = agegrp, y = or, color = udd)) +
  geom_point(size = 3) +
  geom_segment(aes(x = agegrp, xend = agegrp,
                   y = lower, yend = upper)) +
  theme_bw()

I tried adding some jitter, but it looks too random:

enter image description here

ggplot(df, aes(x = agegrp, y = or, color = udd)) +
  geom_point(size = 3,
             position = position_jitter(width = 0.3, 
                                        seed = 1)) +
  geom_segment(aes(x = agegrp, xend = agegrp,
                   y = lower, yend = upper), 
               position = position_jitter(width = 0.3,  
                                          seed = 1)) +
  theme_bw()

How can I obtain something more ordered, e.g.:

enter image description here

Data

set.seed(1)
df <- data.frame(
  agegrp = rep(c("18-39", "40-69", "70+"), 3),
  udd = c(rep("V", 3), rep("E", 3), rep("G", 3)),
  or = runif(9, min = 1.1, max = 3.9),
  lower = runif(9, min = 0.6, max = 2.7),
  upper = runif(9, min = 3.2, max = 6.7)
)

Solution

  • One option would be to use geom_pointrange with position_dodge:

    library(ggplot2)
    
    ggplot(df, aes(x = agegrp, y = or, color = udd)) +
      geom_pointrange(
        aes(
          ymin = lower, ymax = upper
        ),
        position = position_dodge(width = 0.75)
      ) +
      theme_bw()
    

    enter image description here