首页 > 解决方案 > 使用 ggplot2 将平均值添加到 R 中的分组箱形图

问题描述

我在两种温度(27C 和 31C)及其密度下拥有三种藻类培养物(A、B、C)。我想制作一个箱形图,其中 x 轴为温度,y 轴为密度,每个温度以上的三种文化(见下图)。我还需要包含一个带有每个培养物和温度的平均密度的点。我的脚本仅在每个温度上方绘制一个平均值,但我需要的是 A@27C、B@27C、C@27 和 A@31C、B@31C 和 C@31C 的平均值。我试图调整一些有类似问题的脚本,但我无法让它工作。任何帮助将非常感激。

graph<-ggplot(Algae, aes(x = Temperature, 
                         y = Density,
                         fill=Culture))+
              geom_boxplot()+
              stat_summary(fun=mean, 
                           geom="point", 
                           shape=20, 
                           size=2, 
                           color="red", 
                           fill="red", 
                           position = position_dodge2 (width = 0.5, preserve = "single"))

在此处输入图像描述

标签: r

解决方案


删除fillinstat_summary并调整widthinposition 以下是mtcars数据集的示例:

ggplot(mtcars, aes(x = factor(am),
                   y = mpg,
                   fill=factor(cyl)))+
  geom_boxplot() +
  stat_summary(fun=mean, 
               geom="point",
               shape=20, 
               size=2, 
               color="red", 
               position = position_dodge2 (width = 0.7, preserve = "single"))

在此处输入图像描述


推荐阅读