如何在R ggdensity函数中显示均值?

问题描述 投票:0回答:1

任何想法如何在下图中显示虚线(均值)的值?

非常感谢。

library(ggpubr)
#> Loading required package: ggplot2
#> Loading required package: magrittr
# Create some data format
# :::::::::::::::::::::::::::::::::::::::::::::::::::
set.seed(1234)
wdata = data.frame(
   sex = factor(rep(c("F", "M"), each=200)),
   weight = c(rnorm(200, 55), rnorm(200, 58)))
head(wdata, 4)
#>   sex   weight
#> 1   F 53.79293
#> 2   F 55.27743
#> 3   F 56.08444
#> 4   F 52.65430

# Density plot with mean lines and marginal rug
# :::::::::::::::::::::::::::::::::::::::::::::::::::
# Change outline and fill colors by groups ("sex")
# Use custom palette
ggdensity(wdata, x = "weight",
   add = "mean", rug = TRUE,
   color = "sex", fill = "sex",
   palette = c("#00AFBB", "#E7B800"))

enter image description here

r add mean
1个回答
0
投票

您可以通过使用aggregate计算每个组的平均值,并使用此输出来提供geom_text函数:

aggregate(weight~sex, data = wdata, FUN = mean)

  sex   weight
1   F 54.94224
2   M 58.07325

这里是它在geom_text中的使用:

ggdensity(wdata, x = "weight",
          add = "mean", rug = TRUE,
          color = "sex", fill = "sex",
          palette = c("#00AFBB", "#E7B800"))+
  geom_text(data = aggregate(weight~sex, data = wdata, FUN = mean),
            aes(x = weight, y = Inf, color = sex, label = round(weight,2)), 
            vjust = 1)

enter image description here

它回答了您的问题吗?

© www.soinside.com 2019 - 2024. All rights reserved.