R 中多元回归的绘图"regression line"



我用几个连续的预测因子进行了多元回归,其中一些预测因子是显著的,我想创建一个散点图或类似散点的DV图,对照一个预测因子,包括一条"回归线"。我该怎么做?

我的情节看起来像这个

D = my.data; plot( D$probCategorySame, D$posttestScore )

如果是简单的回归,我可以添加这样的回归线:

lmSimple <- lm( posttestScore ~ probCategorySame, data=D )
abline( lmSimple ) 

但我的实际模型是这样的:

lmMultiple <- lm( posttestScore ~ pretestScore + probCategorySame + probDataRelated + practiceAccuracy + practiceNumTrials, data=D )

我想添加一条回归线,反映实际模型的系数和截距,而不是简化模型。为了做到这一点,我想我很乐意假设所有其他预测因素的平均值,尽管我已经准备好听取相反的建议。

这可能没有什么区别,但我会提到以防万一,情况稍微复杂了一点,因为我可能不想绘制原始数据。相反,我想为预测器的装箱值绘制DV的平均值,就像这样:

D[,'probCSBinned'] = cut( my.data$probCategorySame, as.numeric( seq( 0,1,0.04 ) ), include.lowest=TRUE, right=FALSE, labels=FALSE )
D = aggregate( posttestScore~probCSBinned, data=D, FUN=mean )
plot( D$probCSBinned, D$posttestScore )

只是因为当我这样做的时候,我的数据看起来更干净。

要绘制线性或广义线性模型中的各个项(即,与lmglm拟合),请使用termplot。无需装箱或其他操作。

# plot everything on one page
par(mfrow=c(2,3))
termplot(lmMultiple)
# plot individual term
par(mfrow=c(1,1))
termplot(lmMultiple, terms="preTestScore")

您需要在绘图的域中创建一个x值的向量,并从模型中预测它们对应的y值。要做到这一点,您需要将这个向量注入到一个由与模型中的变量匹配的变量组成的数据帧中。你说你可以将其他变量固定在它们的平均值,所以我在解决方案中使用了这种方法。考虑到绘图中的其他值,您预测的x值是否真的合法可能是您在设置时需要考虑的问题。

如果没有样本数据,我不能确定这是否适用于您,所以如果下面有任何错误,我很抱歉,但这至少应该说明这种方法。

# Setup
xmin = 0; xmax=10 # domain of your plot
D = my.data
plot( D$probCategorySame, D$posttestScore, xlim=c(xmin,xmax) )
lmMultiple <- lm( posttestScore ~ pretestScore + probCategorySame + probDataRelated + practiceAccuracy + practiceNumTrials, data=D )
# create a dummy dataframe where all variables = their mean value for each record
# except the variable we want to plot, which will vary incrementally over the 
# domain of the plot. We need this object to get the predicted values we
# want to plot.
N=1e4
means = colMeans(D)
dummyDF = t(as.data.frame(means))
for(i in 2:N){dummyDF=rbind(dummyDF,means)} # There's probably a more elegant way to do this.
xv=seq(xmin,xmax, length.out=N)
dummyDF$probCSBinned = xv 
# if this gives you a warning about "Coercing LHS to list," use bracket syntax:
#dummyDF[,k] = xv # where k is the column index of the variable `posttestScore`
# Getting and plotting predictions over our dummy data.
yv=predict(lmMultiple, newdata=subset(dummyDF, select=c(-posttestScore)))
lines(xv, yv)

查看TeachingDemos软件包中的Predict.Plot函数,可以选择绘制一个预测器与其他预测器给定值下的响应。

最新更新