针对多个因素绘制箱线图并使用 ggplot2 在 R 中覆盖原始数据

Plotting a boxplot against multiple factors and overlay raw data in R with ggplot2

我有这样的箱线图;

library(ggplot2)
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot(aes(fill = factor(am)))

所以这会将数据绘制为箱形图,它是两个因素的基础,一个有两个水平,另一个有三个水平。

现在我想叠加原始数据。 但是如果我添加 geom_points;

p <- ggplot(mtcars, aes(factor(cyl), mpg))
p + geom_boxplot(aes(fill = factor(am))) +
geom_point()

它忽略了其中一个因素,并在分组箱线图的中间绘制折叠的原始数据。

是否有简单的解决方法,以便 geom_points 实际上绘制正确?

谢谢!

您需要按照 geom_boxplot:

的默认方式定位点
ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(am))) + 
  geom_boxplot() + 
  geom_point(position = position_dodge(width = .7))