简体   繁体   English

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

[英]How to create a graph showing the predictive model, data and residuals in R

Given two variables, x and y , I run a dynlm regression on the variables and would like to plot the fitted model against one of the variables and the residual on the bottom showing how the actual data line differs from the predicting line.给定两个变量xy ,我对这些变量运行 dynlm 回归,并希望针对其中一个变量绘制拟合模型,底部的残差显示实际数据线与预测线的不同之处。 I've seen it done before and I've done it before, but for the life of me I can't remember how to do it or find anything that explains it.我以前见过它做过,我以前也做过,但对于我的生活,我不记得怎么做或找到任何可以解释它的东西。

This gets me into the ballpark where I have a model and two variables, but I can't get the type of graph I want.这让我进入了球场,在那里我有一个模型和两个变量,但我无法获得我想要的图表类型。

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

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

I want to generate a graph that looks like this where you see the model and the real data overlaying each other and the residual plotted as a separate graph on the bottom showing how the real data and the model deviate.我想生成一个看起来像这样的图表,您可以看到模型和真实数据相互重叠,残差绘制为底部的单独图表,显示真实数据和模型如何偏离。目标

This should do the trick:这应该可以解决问题:

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'

and this is the code for plotModel ,这是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()  
}

在此处输入图片说明

what you're looking for is resid(model) .你要找的是resid(model) Try this:尝试这个:

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM