使用 geom_vline 在多个面的密度图中插入平均线 结果

问题描述

对于下面的数据集,我想使用密度图来比较以下变量在两种性别中的分布:withdraw、affect 和 estress。这些图还应包含描绘每个性别变量均值的垂直线,并绘制在具有不同方面的同一图形上。

我当前的代码如下,但是我不知道如何使用 geom_vline 来获取每个方面的平均值:

vars_2_plot <- names(estress.dat1)[!names(estress.dat1) %in% "sex"]
estress.dat1 %>%
  pivot_longer(cols = all_of(vars_2_plot),names_to = "Predictors",values_to = "Values"
    ) %>%
  ggplot( aes(x = Values,fill = factor(sex) )) +   
  geom_density(alpha = 0.3) +
  facet_wrap(~ Predictors,scales = "free") +
  theme_minimal() +
labs(fill = "sex",x = "Predictor values") 

我的数据:

structure(list(withdraw = c(3,1,3.66,4.66,4.33,3,2,4,5,1.66,1.33,2.33,2.66,3.33,6.33,7,4),affect = c(2.6,2.4,1.16,1.5,1.83,3.16,2.16,1.4,3.83,2.83,4.16,3.5,2.5,1.6,1.5),estress = c(6,5.5,4.5,6,6.5,5.5),sex = structure(c(2L,1L,2L,1L
),.Label = c("0","1"),class = "factor")),row.names = c(NA,-262L),class = "data.frame")

解决方法

对于 data= 中的 geom_vline 参数,您需要一个数据框,其列与您的构面变量相同,以及您可以使用 colmeans 计算的相应平均值。

library(magrittr);library(tidyr);library(ggplot2)
vars_2_plot <- names(estress.dat1)[!names(estress.dat1) %in% "sex"]

estress.dat1 %>%
  pivot_longer(cols=all_of(vars_2_plot),names_to="Predictors",values_to="Values"
  ) %>%
  ggplot(aes(x=Values,fill=factor(sex) )) +   
  geom_density(alpha=0.3) +
  geom_vline(data=data.frame(means=colMeans(estress.dat1[-4]),Predictors=colnames(estress.dat1[-4])),aes(xintercept=means),color="red") +
  facet_wrap(~ Predictors,scales="free") +
  theme_minimal() +
  labs(fill="sex",x="Predictor values")

结果

enter image description here