【发布时间】:2019-05-22 02:50:58
【问题描述】:
我正在运行一个线性模型,并希望创建一个框架来可视化我的 actual 与 fitted 值,使用 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'
目标是将我的actual 和fitted 值放在同一个轴上的一个图表中(并最终在残差中分层以获得更完整的图片)。
【问题讨论】:
-
把最后一行改成
lmodel_plot + geom_line(aes(y = fitted)),你只是忘了aes/aesthetic部分。 -
ggplot也有函数geom_smooth(method = "lm")将显示拟合线。如果您只想查看关系,则可以省去在data.frame中创建附加列的步骤。