在大多数情况下,您将无法将点放置在每个分组框中,因为它们通过轴相互重叠。一种替代方法是使用facet_wrap。
这里是iris数据的一个例子:
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, fill=Species)) +
geom_point(aes(color = Species), shape = 20, size = 3) +
geom_boxplot(alpha = 0.8) +
facet_wrap(~Species)
如果您不希望点的颜色与箱线图的颜色相同,则必须从 geom_point 内的 aes 中删除分组变量。同样,以iris 为例,
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, fill=Species)) +
geom_boxplot(alpha = 0.8) +
geom_point(shape = 20, size = 3, color = 'red') +
facet_wrap(~Species)
请注意,ggplot2 包是分层工作的。因此,如果在geom_boxplot 图层之后添加geom_point 图层,这些点将位于箱线图的顶部。如果在geom_boxplot 图层之前添加geom_point 图层,则这些点将在背景中。
编辑:
如果您想要在箱线图中添加一个点来表示平均值,您可以执行以下操作:
iris %>%
group_by(Species) %>%
mutate(mean.y = mean(Sepal.Width),
mean.x = mean(Sepal.Length)) %>%
ggplot(aes(x=Sepal.Length, y=Sepal.Width, fill=Species)) +
geom_boxplot(alpha = 0.8) +
geom_point(aes(y = mean.y, x = mean.x), shape = 20, size = 3, color = 'red')
但请注意,它可能需要在 x 轴上进行一些校准,以使其恰好位于每个框的中间。