出于某种愚蠢的原因,我需要创建一个箱线图,其中的中线是平均值而不是中位数。我已经检查了stackoverflow,并找到了添加平均线的示例,但并不完全是我需要的。我尝试使用stat_smooth但没有骰子。有任何想法吗?
下面的代码:
dust <- c(4.5, 3.7, 5, 5.2, 8.5, 6.6, 4.7, 5, 5.7, 4.3, 2.3, 7.6, 5.2,
6, 8.7, 7.5, 7.7, 11, 9, 6.5, 8.7, 5, 2.2, 7.5, 7.5, 3.5)
wind <- c("Present", "Absent", "Absent", "Absent", "Absent", "Absent",
"Absent", "Absent", "Absent", "Present", "Absent", "Absent",
"Present", "Present", "Absent", "Absent", "Absent", "Absent",
"Absent", "Present", "Absent", "Present", "Absent", "Absent",
"Absent", "Present")
df <- data.frame(dust,wind)
plot <- ggplot(data=df,aes(x=wind,y=dust))+geom_boxplot()+stat_smooth()
plot
Run Code Online (Sandbox Code Playgroud)
有几种方法可以做到这一点:
最简单的方法是简单地调用:
plot <- ggplot(data = df, aes(y = dust, x = wind)) +
geom_boxplot(aes(middle = mean(dust))
Run Code Online (Sandbox Code Playgroud)
您还可以利用中的fatten参数geom_boxplot()。这控制中线的粗细。如果将其设置为NULL,则不会绘制中线,并且可以使用插入一条均值线stat_summary。
plot <- ggplot(data = df, aes(y = dust, x = wind)) +
geom_boxplot(fatten = NULL) +
stat_summary(fun.y = mean, geom = "errorbar", aes(ymax = ..y.., ymin = ..y..),
width = 0.75, size = 1, linetype = "solid")
print(plot)
Run Code Online (Sandbox Code Playgroud)
输出使用 fatten = NULL
如您所见,上面的方法可以很好地进行绘制,但是当您评估代码时,它会输出一些警告消息,因为fatten实际上并没有期望值NULL。
好的方面是,此方法可能更灵活一些,因为我们实质上是在“擦除”中间线并添加所需的任何内容。例如,我们还可以选择保留中位数,并将平均值添加为虚线。
ggplot(df) +
geom_boxplot(
aes(
x = wind, ymin = min(dust), lower = quantile(dust, .25),
middle = mean(dust), upper = quantile(dust, .75),
ymax = max(dust)
), stat = "identity"
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6414 次 |
| 最近记录: |