【问题标题】:Add mean to grouped box plot in R with ggplot2使用 ggplot2 将平均值添加到 R 中的分组箱形图
【发布时间】:2021-02-20 05:54:09
【问题描述】:

我用 ggplot2 在 R 中创建了一个分组箱线图。但是,当我想添加平均值时,点会出现在组中的两个框之间。如何更改它以使每个框内都有点?

这是我的代码:

ggplot(results, aes(x=treatment, y=effect, fill=sex)) + 
  geom_boxplot() +
  stat_summary(fun.y=mean, geom="point", shape=20, size=3, color="red")`

【问题讨论】:

    标签: r ggplot2 mean boxplot


    【解决方案1】:

    您可以使用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"))
    

    【讨论】:

      【解决方案2】:

      在大多数情况下,您将无法将点放置在每个分组框中,因为它们通过轴相互重叠。一种替代方法是使用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 轴上进行一些校准,以使其恰好位于每个框的中间。

      【讨论】:

        猜你喜欢
        • 2018-11-25
        • 2020-05-02
        • 2023-04-03
        • 2018-03-11
        • 1970-01-01
        • 2020-05-12
        • 1970-01-01
        • 2021-01-31
        相关资源
        最近更新 更多