r:使用 lm 和 ggplot2 生成拟合图与实际图

r: generating fitted vs. actual plots using lm and ggplot2

我正在 运行 建立一个线性模型,我想创建一个框架来可视化我的 actualfitted 值,使用 ggplot2 快速、可重现这样当我 运行 一个模型时,我可以快速调出最新的 运行 并查看我在哪里有最大的残差。

我已经为 运行 创建了一个示例数据集,但是在将拟合值添加到可视化(仅 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 值放在同一个轴上的一个图表中(并最终在残差中分层以获得更完整的图片)。

您的绘图功能已关闭,您的模型 Var1 vs 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 来绘制实际点。

您忘记了 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))

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

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