【问题标题】:R: generate plot for multiple regression model with interaction between polynomial numeric predictor and factorR:为多项式数值预测变量和因子之间的交互生成多元回归模型图
【发布时间】:2013-12-16 06:00:30
【问题描述】:

我正在尝试根据我的数据生成一个绘图,并在这些数据上运行一个多元回归模型。但是,我无法将我需要的所有内容都绘制在一个图表中(即原始数据点 + 拟合线 + 95% CI)。在这个模型中,有一个多项式数值预测器与一个因子(三个水平)相互作用,所以我将在图中有三个拟合线。

#Here are the data
list<-c(60,75,90,120,180)
x1<-rep(list,each=3,times=3) #predictor 1
x2<-rep(seq(1:3),each=15) #predictor 2
y<-c(72, 63, 58, 56, 50, 52, 47, 48, 51, 41, 47, 44, 38, 34, 36, 92, 93, 88, 76, 76, 74, 72, 67, 78, 56, 71, 65, 53, 56, 60, 93, 73, 77, 96, 79, 81, 84, 79, 86, 80, 76, 75, 69, 61, 63)
df<-data.frame(cbind(x1,x2,y)) #combine vectors into data frame
df$x2<-factor(df$x2) #make x2 a factor

#here is the model
mod<-lm(y~poly(x1,2)*x2,data=df)

我更喜欢从空地开始,然后从那里开始。我可以轻松绘制原始数据,但我不确定如何从此处添加的模型中获取拟合线和 95% 置信区间。

#create empty plot
plot(y~x1,xlim=c(min(x1),max(x1)),ylim=c(min(y),max(y)),
 type="n",xlab="x1",ylab="y",data=df)

#add data points
points(y[x2==1]~x1[x2==1], cex=1.7,pch=21,lwd=2,bg="gray10", data=df)
points(y[x2==2]~x1[x2==2], cex=1.7,pch=22,lwd=2,bg="gray40", data=df)
points(y[x2==3]~x1[x2==3], cex=1.7,pch=25,lwd=2,bg="gray80", data=df)

通过大量研究和修补,我想出了如何使用“效果”包获得拟合线和 95% CI,但我不知道如何将原始数据添加到该图中。

library(effects)
plot(allEffects(mod,xlevels=list(x1=min(x1):max(x1)),xlab="x1",ylab="y"),multiline=T,rug=F,ci.style="bands")

这需要大量的写作和代码,但我希望我想要做的事情是明确的。非常感谢您的帮助。

【问题讨论】:

  • 您好,我怀疑如果您充分结合您的问题,您将有更好的运气来寻求有用的答案。具体来说,在您的第三段中的某处,有一句话说“我不知道如何...”,这可以作为一个单一的简化问题。

标签: r plot regression quadratic-curve


【解决方案1】:

predict 函数使用正交多项式处理所有杂乱的计算:

x.two <- df$x2
lines(x = sort(x.two),
      y = predict(mod, newdata=data.frame(x1=factor("1"), x2=sort(x.two) ) ) ,
      col="red")
 lines(x = sort(x.two),
       y = predict(mod, newdata=data.frame(x1=factor("2"), x2=sort(x.two) ) ) ,
       col="green")
 lines(sort(x.two),
       predict(mod,  newdata=data.frame(x1=factor("3"),x2=sort(x.two) ) ) , col="orange")

【讨论】:

  • 感谢 DWin!这很有帮助。我在您的答案中添加了 95% 的 CI。
猜你喜欢
  • 2018-10-19
  • 2014-05-01
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多