2013-01-22 125 views
7

我想使线性回归的下面的情况中的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画线?

+2

有了多个回归系数,回归并不代表一条线。也许你想stats :: decompose。 –

回答

7

您正在寻找的predict功能?

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

enter image description here

您也可以使用这个预测未来的数据与计算的系数对齐。例如。

# 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) 

enter image description here

+0

谢谢@thelatemail,但你能告诉我为什么它不起作用(a = 0,b = 1)? – Little

+1

预测没有直线。 –

+0

是的,你是对的@DWin,我认识到我的错误,它是一个多项式模型,所以这就是为什么没有直线,我的坏 – Little

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)) 

enter image description here

+1

这是“正确的”答案。年份和季度是“独立”的概念是错误的(人们甚至可以说是荒谬的)。 –

+1

@Dwin - 你能解释一下吗?难道你不能有一个线性的温度总体上升的情景,但每个季节的温度波动吗?这会使我的“基于预测”的答案在统计上无效吗?也许我错过了你正在创造的点。 – thelatemail

+0

你是对的@thelatemail,这个例子来自一本书,它考虑了消费者价格指数的年份和季度内每季度的波动 – Little

6

Humbug的。这些都是合理的解决方案,但他们不会按照你的要求去做。现在你要求的是稍微凉爽一点,完全不切实际,但可以使用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)) 

现在在魔术发生在rgl

library(rgl) 

persp3d(x, y, z, col="lightblue") 

enter image description here

它不这样做正义在这里,但它的漂亮,你可以将它一下。

什么是地狱,让我们添加原始的点

points3d(year, quarter, cpi, size=5, col="red") 

enter image description here

+1

我从来没有真正喜欢3D图的可读性方面,但有一个+1明确回答这个问题。 – thelatemail

+0

@thelatemail如果你真的使用rgl设备并移动这个数字,它们会更具可读性。 Luke Tierney写了[关于如何将动态图嵌入到pdf中](http://www.stat.uiowa.edu/~luke/R/misc3d/misc3d-pdf/),但我没有尝试过。 –

+0

Humbug的确如此。前进。解释那架飞机。 –

2

的错误就在于你的数据被格式化的方式。这是另一种选择:

year<-seq(from=2008,to=2010.75,by=.25) 
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) 
df <- data.frame(year,cpi) 
plot(df)+abline(lm(df$cpi~df$year)) 

enter image description here

然后,如果你喜欢,你可以重新格式化轴标签。

+3

这忽略了这个季度,因此不是问题的答案。 –

1

TeachingDemos包中的Predict.PlotTkPredict函数将绘制其中一个预测变量和响应变量之间的关系,该变量以其他预测变量的值为条件。 Predict.Plot可以非常简单地查看来自不同条件的多行,而TkPredict可让您交互式更改受限制的值(并将生成Predict.Plot代码以重新创建当前图)。

这些函数通常用于多个预测变量的回归模型,但不会像时间序列中的分解一样好。