2012-10-02 38 views
7

給定兩個變量xy,我對這些變量運行dynlm迴歸,並打算將擬合模型與一個變量和殘差底部顯示實際數據線與預測線的不同之處。我以前見過它,之前我做過,但在我的生活中,我不記得如何去做或找到解釋它的任何事情。如何在R中創建一個顯示預測模型,數據和殘差的圖表

這讓我進入球場,我有一個模型和兩個變量,但我不能得到我想要的圖形類型。

library(dynlm) 
x <- rnorm(100) 
y <- rnorm(100) 
model <- dynlm(x ~ y) 

plot(x, type="l", col="red") 
lines(y, type="l", col="blue") 

我要生成看起來像這樣的,你看到的模型和實際數據彼此覆蓋,剩餘繪製成的底部有一個單獨的圖形顯示圖形的實際數據和模型偏離如何。 The Objective

+0

我希望我可以選擇這兩個答案。他們都拉掉了我需要他們做的事情。我打算和裏卡多的回答完全一致,因爲它增加了信心包圍盒。 – FloppyDisk

回答

9

這應該做的伎倆:

library(dynlm) 
set.seed(771104) 
x <- 5 + seq(1, 10, len=100) + rnorm(100) 
y <- x + rnorm(100) 
model <- dynlm(x ~ y) 

par(oma=c(1,1,1,2)) 
plotModel(x, model) # works with models which accept 'predict' and 'residuals' 

,這是爲plotModel代碼,

plotModel = function(x, model) { 
    ymodel1 = range(x, fitted(model), na.rm=TRUE) 
    ymodel2 = c(2*ymodel1[1]-ymodel1[2], ymodel1[2]) 
    yres1 = range(residuals(model), na.rm=TRUE) 
    yres2 = c(yres1[1], 2*yres1[2]-yres1[1]) 
    plot(x, type="l", col="red", lwd=2, ylim=ymodel2, axes=FALSE, 
     ylab="", xlab="") 
    axis(1) 
    mtext("residuals", 1, adj=0.5, line=2.5) 
    axis(2, at=pretty(ymodel1)) 
    mtext("observed/modeled", 2, adj=0.75, line=2.5) 
    lines(fitted(model), col="green", lwd=2) 
    par(new=TRUE) 
    plot(residuals(model), col="blue", type="l", ylim=yres2, axes=FALSE, 
     ylab="", xlab="") 
    axis(4, at=pretty(yres1)) 
    mtext("residuals", 4, adj=0.25, line=2.5) 
    abline(h=quantile(residuals(model), probs=c(0.1,0.9)), lty=2, col="gray") 
    abline(h=0) 
    box() 
} 

enter image description here

7

你在找什麼是resid(model)。試試這個:

library(dynlm) 
x <- 10+rnorm(100) 
y <- 10+rnorm(100) 
model <- dynlm(x ~ y) 

plot(x, type="l", col="red", ylim=c(min(c(x,y,resid(model))), max(c(x,y,resid(model))))) 
lines(y, type="l", col="green") 
lines(resid(model), type="l", col="blue") 

enter image description here

相關問題