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:
How can I center the points on each respective bin?
CodePudding user response:
Unlike
geom_boxplot()
,geom_point()
doesn't dodge by default -- you need to specifyposition = position_dodge()
.This still won't quite work, because there are some
NA
s infactor
-- this will cause your points to be dodged across three groups, which won't align correctly. You can remove theNA
s usingdrop_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))