代码之家  ›  专栏  ›  技术社区  ›  ykl

geom\u smooth()和facet\u grid()与mgcv:::gam和by=“”

  •  2
  • ykl  · 技术社区  · 7 年前

    我比较了通过ggplot2的geom\u平滑(使用facet\u网格)执行的gam与使用mgcv:::gam(使用visreg可视化的指定“by”因子)执行的gam的输出。随附数据和代码:

    library(dplyr)
    set.seed(1)
    dat <- iris %>% mutate(response = sample(rep(c(0,1),length.out=150/2),150, replace=T))
    
    #Just the output from geom_smooth
    library(ggplot2)
    ggplot(dat, aes(Sepal.Length,response)) +
      geom_point() +
      geom_smooth(method="gam", formula = y~s(x, bs="cs"), method.args=list("binomial")) +
      facet_grid(.~Species)
    #Now performing the gam through mgcv:::gam specifying by=Species
    library(mgcv)
    gam <- gam(dat, formula = response~s(Sepal.Length, bs="cs", by=Species),family = binomial())
    #Comparing the two different outputs
    library(visreg)
    visreg(gam, "Sepal.Length", by="Species", scale="response", gg=T)  +
      guides(color=F)+
      geom_smooth(data=dat,aes(Sepal.Length,response),
                  method="gam", formula = y~s(x, bs="cs"), method.args=list("binomial"), color="red", fill="green")
    

    geom_smooth output shown with red smooth and green CI, mgcv with blue smooth and grey CI

    基本上,我认为发生的是,mgcv:::gam将其gam平滑基于某些类型的“插补”数据,这些数据用于每个物种水平实际上没有的区域。geom_smooth()中的设置似乎可以避免这种情况。有谁知道如何抵消这一点,以便geom_smooth和mgcv:::gam的输出相同?

    编辑:

    根据user20650的回答,代码更新为:

    library(mgcv)
    gam <- gam(dat, formula = response~Species + s(Sepal.Length, bs="cs", by=Species),family = binomial()) 
    library(visreg)
    visreg(gam, "Sepal.Length", by="Species", scale="response", gg=T)  +
      guides(color=F)+
      geom_smooth(data=dat,aes(Sepal.Length,response),
                  method="gam", formula = y~s(x, bs="cs"), method.args=list("binomial"), color="red", fill="green",
                  fullrange=T)
    

    updated plot

    从上图中可以看出,这两种方法存在细微差异(主要在CI中)。如果我们看set,这一点会更加突出。种子(100):

    library(dplyr)
    set.seed(100)
    dat <- iris %>% mutate(response = sample(rep(c(0,1),length.out=150/2),150, replace=T))
    
    library(mgcv)
    gam <- gam(dat, formula = response~Species + s(Sepal.Length, bs="cs", by=Species),family = binomial()) 
    library(visreg)
    visreg(gam, "Sepal.Length", by="Species", scale="response", gg=T)  +
      guides(color=F)+
      geom_smooth(data=dat,aes(Sepal.Length,response),
                  method="gam", formula = y~s(x, bs="cs"), method.args=list("binomial"), color="red", fill="green",
                  fullrange=T) 
    

    new seed plot

    有谁能解释这两种方法的区别,以及如何从mgcv:::gam中的geom_smooth()生成相同的输出,反之亦然(在全范围=T以及全范围=F的情况下)?

    0 回复  |  直到 7 年前