【问题标题】:Fitting a line to the mean values of a multilevel variable using geom_smooth使用 geom_smooth 将一条线拟合到多级变量的平均值
【发布时间】:2022-05-03 07:40:38
【问题描述】:

我有这个dataframe

我在 y 轴“值”和 x 轴上创建了一个图,表示“Column_S”的每个级别,其中包含从 S1 到 S10 的级别。所有这些都按“VS”和“Inst”(带有 facet_grid)和带有颜色的“Estatus”分组。

na.omit(data) %>% 
  group_by(VS,Estatus,Inst, Columna_S) %>% 
  summarise(media = mean(value), 
            desvio = sd(value),                             
            error_est = desvio / sqrt(n()),            
            intervalo_sup = media + (2*error_est),      
            intervalo_inf = media - (2*error_est)) -> stats

ggplot() +  
  geom_errorbar(
    data = stats,   
    aes(x = Columna_S,
        ymin = intervalo_inf,
        ymax = intervalo_sup,
        color = Estatus   
    ), width = 0.4 )+
  geom_point(data = stats,
             aes(x = Columna_S,
                 y = media,
             color = Estatus))+
  facet_grid(Inst ~ VS, scales = "free") +
  theme_classic()  

但是,我想使用geom_smooth 绘制一条适合沿 x 轴的均值的线(加上标准误差),而不是每个均值的独立点。

我已经尝试了下面的代码,但它没有产生预期的结果。

na.omit(data) %>% 
  ggplot(aes(x=Columna_S,y=value,colour=Estatus, na.rm = TRUE) ) +
  geom_smooth(aes(fill=Estatus,na.rm = TRUE)) +
  scale_y_continuous(breaks = seq(0,100, by=25), limits=c(0,100))+
  facet_grid(Institution~Value_system, scales = "free")+
  theme_classic()  

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您在 x 轴上有因素,我不太确定将一条平滑线穿过它是否有意义,但如果这是您需要的,它是这样的:

    data %>% 
    filter(!is.na(Columna_S)) %>%
    ggplot(aes(x=Columna_S,y=value,colour=Estatus)) +
    geom_smooth(aes(group=Estatus)) +
    facet_grid(Inst~VS, scales = "free")+
    theme_classic() 
    

    你可以考虑通过各种方式划线:

    data %>% 
    filter(!is.na(Columna_S)) %>%
    ggplot(aes(x=Columna_S,y=value,colour=Estatus)) +
    stat_summary(aes(group=Estatus),fun=mean,geom="line") +
    facet_grid(Inst~VS, scales = "free")+
    theme_classic()
    

    【讨论】:

    • 感谢@StupidWolf,尽管当我尝试在 y 轴 scale_y_continuous(breaks = seq(0,100, by=25), limits=c(0,100)) 上设置相同的比例时,它并没有正确绘制 se。我认为这与我在 x 轴上有因素有关。无论如何,感谢您的回答,这很有帮助。
    • 是的,我注意到在制作情节时..问题是平滑时,误差线超出了您的限制。因此您可以更改平滑参数或使用 se=FALSE 省略标准误差
    【解决方案2】:

    晚了一年,但是……

    我有一个类似的问题,我有一个有序因子,并且想要通过水平线拟合一条直线,但上面的解决方案不起作用:没有给出错误,只是图上没有线条。

    我找到的解决方案很有效,因为在 ggplot 中,您可以将数据集绘制在彼此之上(您不仅限于一个数据框)。 所以,

    1. 创建因子的数字版本
    2. 使用上面的刻面等绘制箱线图
    3. 然后在因子层的顶部绘制一个 geom_smooth 层 提及 data=(相同的数据框)和
    4. 使用数字因子作为该层的 x,保持相同的 y。

    有效!因为因子值 = 线条绘制在正确位置的数值。 如果仍然需要,我可以添加代码。

    【讨论】:

    • 嗨@DaveG,我今天看到了你的答案。谢谢!我也解决了这个问题,但我认为发布您的代码以便其他用户将来可以使用它是个好主意!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多