2009-09-08 67 views
15

为了帮助填充R标签,我发布了一些我经常从学生处收到的问题。多年来,我已经为自己找到了自己的答案,但也许有更好的方法可以解决我不知道的问题。从线性模型中绘制交互效果的最佳方法

的问题:我刚跑了回归连续yx但是因素f(其中levels(f)产生c("level1","level2")

thelm <- lm(y~x*f,data=thedata) 

现在我想通过x按组划分绘制的y的预测值由f定义。我得到的所有情节都很丑陋,并显示太多线条。

我的回答:尝试predict()函数。

##restrict prediction to the valid data 
##from the model by using thelm$model rather than thedata 

thedata$yhat <- predict(thelm, 
     newdata=expand.grid(x=range(thelm$model$x), 
          f=levels(thelm$model$f))) 

plot(yhat~x,data=thethedata,subset=f=="level1") 
lines(yhat~x,data=thedata,subset=f=="level2") 

还有其他的想法是:(1)更容易理解新手和/或(2)更好从其他角度?

回答

17

效果包具有良好的绘图方法,用于可视化回归的预测值。

thedata<-data.frame(x=rnorm(20),f=rep(c("level1","level2"),10)) 
thedata$y<-rnorm(20,,3)+thedata$x*(as.numeric(thedata$f)-1) 

library(effects) 
model.lm <- lm(formula=y ~ x*f,data=thedata) 
plot(effect(term="x:f",mod=model.lm,default.levels=20),multiline=TRUE) 
3

呵呵 - 仍然试图绕着我的大脑围绕expand.grid()。只是为了比较的缘故,这是我如何(使用GGPLOT2)做到这一点:

thedata <- data.frame(predict(thelm), thelm$model$x, thelm$model$f) 

ggplot(thedata, aes(x = x, y = yhat, group = f, color = f)) + geom_line() 

的ggplot()逻辑是非常直观的,我认为 - 组和颜色用f线。随着小组数量的增加,不必为每个小组指定一个层越来越有用。

+2

请注意,'ggplot2'有一个函数'fortify.lm',它补充了一些线性模型拟合统计数据 – mnel 2012-10-22 22:57:26

2

我在R.不是专家,但是我用:

xyplot(y ~ x, groups= f, data= Dat, type= c('p','r'), 
    grid= T, lwd= 3, auto.key= T,) 

这也是一个选项:

interaction.plot(f,x,y, type="b", col=c(1:3), 
      leg.bty="0", leg.bg="beige", lwd=1, pch=c(18,24), 
      xlab="", 
      ylab="", 
      trace.label="", 
      main="Interaction Plot") 
0

这里是一个小的变化由马特很好的建议和类似的解决方案到赫尔吉,但与ggplot。与上面的区别仅在于我使用了直接绘制回归线的geom_smooth(method ='lm)。

set.seed(1) 
y = runif(100,1,10) 
x = runif(100,1,10) 
f = rep(c('level 1','level 2'),50) 
thedata = data.frame(x,y,f) 
library(ggplot2) 
ggplot(thedata,aes(x=x,y=y,color=f))+geom_smooth(method='lm',se=F)