【问题标题】:r: generating fitted vs. actual plots using lm and ggplot2r:使用 lm 和 ggplot2 生成拟合图与实际图
【发布时间】:2019-05-22 02:50:58
【问题描述】:

我正在运行一个线性模型,并希望创建一个框架来可视化我的 actualfitted 值,使用 ggplot2 以一种快速、可重现的方式,这样当我运行一个模型时,我可以快速拉-up 最新的运行,看看我在哪里有最大的残差。

我创建了一个示例数据集来运行它,但在将拟合值添加到可视化时最终会遇到错误(actual 值本身就很简单)。请参阅下面的示例代码:

# creating sample data set
dfmodel<- data_frame(seq(as.Date('2018-01-01'), as.Date('2018-01-10'), by= 'day'), rnorm(10, 12, 3), rnorm(10, 14, 5))
colnames(dfmodel)<- c( 'date','var1', 'var2')

# running model
lmodel<- lm(var1~ var2, data= dfmodel)

# applying fitted values to my data frame
dfmodel$fitted<- lmodel$fitted.values

# creating ggplot object for visualization
lmodel_plot<- ggplot(dfmodel, aes(x= date, y= var1))
lmodel_plot + geom_line(y= fitted) 

# attempting to layer in fitted value, but generating this error:
Error in rep(value[[k]], length.out = n) : attempt to replicate an object of type 'closure'

目标是将我的actualfitted 值放在同一个轴上的一个图表中(并最终在残差中分层以获得更完整的图片)。

【问题讨论】:

  • 把最后一行改成lmodel_plot + geom_line(aes(y = fitted)),你只是忘了aes/aesthetic部分。
  • ggplot 也有函数geom_smooth(method = "lm") 将显示拟合线。如果您只想查看关系,则可以省去在 data.frame 中创建附加列的步骤。

标签: r ggplot2 lm


【解决方案1】:

您需要同时使用点和线。否则,除非有人知道方法,否则无法(对于此数据)将两个值都绘制为 geom_line

dfmodel %>% 
  ggplot(aes(date,var1))+geom_point(colour="red")+geom_line(aes(y=fitted))

【讨论】:

    【解决方案2】:

    你忘记了 geom_line 的 aes()

    # creating sample data set
    dfmodel<- data_frame(seq(as.Date('2018-01-01'), as.Date('2018-01-10'), by= 'day'), 
    rnorm(10, 12, 3), rnorm(10, 14, 5))
    colnames(dfmodel)<- c( 'date','var1', 'var2')
    
    # running model
    lmodel<- lm(var1~ var2, data= dfmodel)
    
    # applying fitted values to my data frame
    dfmodel$fitted<- lmodel$fitted.values
    
    # creating ggplot object for visualization
    lmodel_plot <- ggplot(dfmodel, aes(x= date, y= var1)) +
      geom_line(aes(y= fitted))
    

    【讨论】:

    • 补充一下为什么最初的尝试给出了如此令人困惑的错误消息:fitted也是一个函数,这意味着geom_line试图将它用作一种参数,必须重复完整长度(就像geom_line(color='red) 将在所有点上重复“红色”)
    【解决方案3】:

    您的绘图功能已关闭,您的模型,Var1 与 Var2,因此您想要绘制 y=Vars 和 x=Var1。

    library(ggplot2)
    # creating ggplot object for visualization
    lmodel_plot<- ggplot(dfmodel, aes(x= var2, y= var1)) +
      geom_point() +geom_line(aes(y= fitted)) 
    
    print(lmodel_plot)
    

    您需要在geom_line 中包含拟合值的美学部分,并且您需要添加geom_point 来绘制实际点。

    【讨论】:

      猜你喜欢
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      相关资源
      最近更新 更多