Home > Blockchain >  R ggplot geom_points not aligned with boxplot bins
R ggplot geom_points not aligned with boxplot bins

Time:02-28

I have a data frame and want to make boxplots and plot geom_points on them. But the points are not centered with the bins. I tried to replicate the issue with the mtcars data frame but wasn't able to so - because it worked there! So I uploaded this data:

enter image description here

How can I center the points on each respective bin?

CodePudding user response:

  1. Unlike geom_boxplot(), geom_point() doesn't dodge by default -- you need to specify position = position_dodge().

  2. This still won't quite work, because there are some NAs in factor -- this will cause your points to be dodged across three groups, which won't align correctly. You can remove the NAs using drop_na(factor).

df <- df %>%
  pivot_longer(cols = c("value1", "value2"), 
               names_to = "new") %>%
  drop_na(factor) %>% 
  group_by(factor, new)

ggplot(df, aes(x = new, y = value, fill = as.factor(factor)))  
  geom_boxplot() 
  geom_point(position = position_dodge(width = .75))
  • Related