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

Lit*_*tle 8 r linear-regression

我想在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)
Run Code Online (Sandbox Code Playgroud)

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

abline(fit)
abline(fit$coefficients[[1]],c(fit$coefficients[[2]],fit$coefficients[[3]]))
Run Code Online (Sandbox Code Playgroud)

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

y=a+b*year+c*quarter
Run Code Online (Sandbox Code Playgroud)

而不是更简单的东西:

y=a+b*year
Run Code Online (Sandbox Code Playgroud)

那么我如何绘制显示线性回归的那条线呢?

是否可以用abline绘制线?

the*_*ail 7

你在寻找这个predict功能吗?

例如:使用lines(predict(fit))会给:

在此输入图像描述

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

# 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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Mat*_*erg 6

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)
cpits <- ts(cpi, start=2008, frequency=4)
plot(decompose(cpits))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


seb*_*n-c 6

骗子.这些都是合理的解决方案,但它们不能满足您的要求.现在你要求的是稍微凉爽和完全不切实际,但可以使用rgl.

f <- function(x, y, coefs){
  z <- coefs[1] + coefs[2] * x + coefs[3] * y
  z
}

x <- seq(from=min(year), to=max(year), length.out=100)
y <- seq(from=min(quarter), to=max(quarter), length.out=100)

z <- outer(x, y, f, coefs=coef(fit))
Run Code Online (Sandbox Code Playgroud)

现在魔术发生在rgl:

library(rgl)

persp3d(x, y, z, col="lightblue")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这里没有公正,但它很漂亮,你可以移动它.

到底是什么,让我们添加你原来的观点

points3d(year, quarter, cpi, size=5, col="red")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述