Dodge geom_points according to specific boxplot group/color

Viewed 208

How can I dodge the geom_points into their specific boxplot group (provided by the aesthetic colour)? I have provided the following (simplified) example:

library(ggplot2)

ggplot(diamonds, aes(x = cut, y = carat, color = color)) +
    geom_boxplot(outlier.shape = NA) +
    geom_point(aes(group = color))

Which provides the following plot:

Boxplot with points not in corresponding boxplot

I would like to have have the points aligned to the boxplot color (group) they belong to. How could I achieve this?

1 Answers

To dodge your points and align them with the box plots use position = position_dodge(width = .75) where .75 is the default width by which box plots get dodged:

library(ggplot2)

ggplot(diamonds, aes(x = cut, y = carat, color = color)) +
  geom_boxplot(outlier.shape = NA) +
  geom_point(aes(group = color), position = position_dodge(width = .75))

Related