Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading