17

为了帮助在这里填充 R 标签,我发布了一些我经常从学生那里收到的问题。多年来,我已经对这些问题提出了自己的答案,但也许还有更好的方法我不知道。

问题:我只是用连续yx但因子f(其中levels(f)产生c("level1","level2"))进行回归

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

现在我想绘制由定义的组分解的y预测xf。我得到的所有情节都很丑陋,而且线条太多。

我的回答:试试这个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)从其他角度更好?

4

4 回答 4

19

效果包有很好的绘图方法来可视化回归的预测值。

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)
于 2009-09-08T17:26:04.857 回答
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 对线条进行分组和着色。随着组数量的增加,不必为每个组指定一个层越来越有用。

于 2009-09-08T17:31:32.847 回答
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")
于 2012-10-22T22:41:22.913 回答
1

这是对 Matt 的出色建议的一个小改动,以及类似于 Helgi 但使用 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)
于 2017-08-22T14:46:09.307 回答