使用 ggplot2 将均值添加到 R 中的分组箱线图
Add mean to grouped box plot in R with ggplot2
我在 R 中使用 ggplot2 创建了一个分组箱线图。但是,当我想添加平均值时,点出现在一组的两个框之间。我怎样才能改变它,使点在每个方框内?
这是我的代码:
ggplot(results, aes(x=treatment, y=effect, fill=sex)) +
geom_boxplot() +
stat_summary(fun.y=mean, geom="point", shape=20, size=3, color="red")`
在大多数情况下,您将无法将点放在每个分组框内,因为它们通过轴彼此重叠。一种替代方法是使用 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
轴进行一些校准,以使其恰好位于每个框的中间。
您可以使用 position_dodge2
。由于点和箱线图的宽度不同,您需要使用 width
参数反复试验以使点集中。
ggplot(mtcars, aes(x=factor(gear), y=hp, fill=factor(vs))) +
geom_boxplot() +
stat_summary(fun.y=mean, geom="point", shape=20, size=3, color="red",
position = position_dodge2(width = 0.75,
preserve = "single"))
我在 R 中使用 ggplot2 创建了一个分组箱线图。但是,当我想添加平均值时,点出现在一组的两个框之间。我怎样才能改变它,使点在每个方框内?
这是我的代码:
ggplot(results, aes(x=treatment, y=effect, fill=sex)) +
geom_boxplot() +
stat_summary(fun.y=mean, geom="point", shape=20, size=3, color="red")`
在大多数情况下,您将无法将点放在每个分组框内,因为它们通过轴彼此重叠。一种替代方法是使用 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
轴进行一些校准,以使其恰好位于每个框的中间。
您可以使用 position_dodge2
。由于点和箱线图的宽度不同,您需要使用 width
参数反复试验以使点集中。
ggplot(mtcars, aes(x=factor(gear), y=hp, fill=factor(vs))) +
geom_boxplot() +
stat_summary(fun.y=mean, geom="point", shape=20, size=3, color="red",
position = position_dodge2(width = 0.75,
preserve = "single"))