如何在R中创建显示预测模型、数据和残差的图表

7
给定两个变量x和y,我对这些变量进行了dynlm回归,并希望绘制拟合模型与其中一个变量的图形,底部显示残差,以展示实际数据线与预测线之间的差异。我以前见过这种图形,并且也做过,但是我现在无法记住如何做或找到任何解释它的东西。
这让我进入了一个领域,我有一个模型和两个变量,但我无法得到我想要的类型的图形。
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

我希望我可以选择两个答案。它们都能做到我需要的事情。但是我要选择Ricardo的答案,因为它添加了置信度边界框。 - FloppyDisk
2个回答

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接