【问题标题】:Custom lm formula in geom_smoothgeom_smooth 中的自定义 lm 公式
【发布时间】:2018-04-11 13:25:22
【问题描述】:

我正在处理多面图,并在geom_smooth() 中使用lm 方法添加线条

d<-data.frame(n=c(100, 80, 60, 55, 50, 102, 78, 61, 42, 18),
              year=rep(2000:2004, 2), 
              cat=rep(c("a", "b"), each=5))

ggplot(d, aes(year, n, group=cat))+geom_line()+geom_point()+
  facet_wrap(~cat, ncol=1)+
  geom_smooth(method="lm")

我想设置一个函数以在适当的情况下应用多项式。我已经制定了一个功能:

lm.mod<-function(df){
  m1<-lm(n~year, data=df)
  m2<-lm(n~year+I(year^2), data=df)
  ifelse(AIC(m1)<AIC(m2), "y~x", "y~poly(x, 2)")
}

但我无法应用它。有什么想法或更好的方法来解决这个问题吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    无法通过单个 geom_smooth 调用应用不同的平滑函数。这是一个基于平滑数据子集的解决方案:

    首先,创建没有geom_smooth 的基础图:

    library(ggplot2)
    p <- ggplot(d, aes(year, n, group = cat)) +
           geom_line() +
           geom_point() +
           facet_wrap( ~ cat, ncol = 1)
    

    其次,函数by用于为cat(用于分面的变量)的每个级别创建一个geom_smooth。该函数返回一个列表。

    p_smooth <- by(d, d$cat, 
                   function(x) geom_smooth(data=x, method = lm, formula = lm.mod(x)))
    

    现在,您可以将geom_smooths 列表添加到您的基础地块中:

    p + p_smooth
    

    该图包括上面板的二阶多项式和下面板的线性平滑:

    【讨论】:

    • 完美 - 非常感谢。这也适用于 dlply:p.smooth1
    【解决方案2】:
    lm.mod<-function(df){
      m1<-lm(n~year, data=df)
      m2<-lm(n~year+I(year^2), data=df)
      p <- ifelse(AIC(m1)<AIC(m2), "y~x", "y~poly(x, 2)")
    return(p) 
    }
    # I only made the return here explicit out of personal preference
    
    ggplot(d, aes(year, n, group=cat)) + geom_line() + geom_point() +
      facet_wrap(~cat, ncol=1)+
      stat_smooth(method=lm, formula=lm.mod(d))
    # stat_smooth and move of your function to formula=
    
    # test by reversing the condition and you should get a polynomial.
    # lm.mod<-function(df){
    #   m1<-lm(n~year, data=df)
    #   m2<-lm(n~year+I(year^2), data=df)
    #   p <- ifelse(AIC(m1)>AIC(m2), "y~x", "y~poly(x, 2)")
    # return(p)
    # }
    

    【讨论】:

    • 我希望在刻面“a”中得到一条曲线,在刻面“b”中得到一条直线。当我运行代码时它不起作用。我错过了什么吗?
    猜你喜欢
    • 2018-08-04
    • 1970-01-01
    • 2018-10-15
    • 2019-08-21
    • 2017-11-30
    • 2021-04-08
    • 2014-09-24
    • 1970-01-01
    • 2021-07-27
    相关资源
    最近更新 更多