2013-01-22 130 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代碼以重新創建當前圖)。

這些函數通常用於多個預測變量的迴歸模型,但不會像時間序列中的分解一樣好。