Press "Enter" to skip to content

如何绘制R中的线性回归?

我想在R中做出以下线性回归的情况

 

year<-rep(2008:2010,each=4)
quarter<-rep(1:4,3)
cpi<-c(162.2,164.6,166.5,166.0,166.4,167.0,168.6,169.5,170.0,172.0,173.3,174.0)
plot(cpi,xaxt="n",ylab="CPI",xlab="")
axis(1,labels=paste(year,quarter,sep="C"),at=1:12,las=3)
fit<-lm(cpi~year+quarter)

 

我想绘制显示我处理的数据的线性回归的线.我尝试过:

 

abline(fit)
abline(fit$coefficients[[1]],c(fit$coefficients[[2]],fit$coefficients[[3]]))

 

问题是我的公式是这样的:

 

y=a+b*year+c*quarter

 

而不是更简单的东西:

 

y=a+b*year

 

那我怎幺能画那条显示线性回归的线?

 

是否有可能用abline绘制线?

 

你在寻找预测函数吗?

 

例如:使用线(预测(拟合))将给出:

 

您还可以使用它来预测将来的数据与计算的系数对齐.例如.

 

# plot the existing data with space for the predicted line
plot(c(cpi,rep(NA,12)),xaxt="n",ylab="CPI",xlab="",ylim=c(162,190))
# plot the future predictions as a line using the next 3 year periods
lines(13:24,
      predict(
        fit,
        newdata=data.frame(year=rep(c(2011,2012,2013),each=4),quarter=rep(1:4,3))
             )
     )
year<-rep(2008:2013,each=4)
axis(1,labels=paste(year,quarter,sep="C"),at=1:24,las=3)

 

翻译自:https://stackoverflow.com/questions/14451782/how-to-plot-the-linear-regression-in-r

Be First to Comment

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注