function lines()不起作用

时间:2013-01-12 14:08:47

标签: r plot lines

我的功能线有问题。

这是我到目前为止所写的:

model.ew<-lm(Empl~Wage)

summary(model.ew)

plot(Empl,Wage)

mean<-1:500 

lw<-1:500

up<-1:500

for(i in 1:500){

  mean[i]<-predict(model.ew,data.frame(Wage=i*100),interval="confidence",level=0.90)[1]

  lw[i]<-predict(model.ew,data.frame(Wage=i*100),interval="confidence",level=0.90)[2]

  up[i]<-predict(model.ew,data.frame(Wage=i*100),interval="confidence",level=0.90)[3]

}

plot(Wage,Empl)

lines(mean,type="l",col="red")

lines(up,type="l",col="blue")

lines(lw,type="l",col="blue")

我的问题是我的情节上没有出现任何线条,我无法找出原因。

有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

您真的需要阅读R的一些介绍性手册。转到此页面,选择一个说明使用R进行线性回归的手册:http://cran.r-project.org/other-docs.html

首先我们需要制作一些数据:

set.seed(42)
Wage <- rnorm(100, 50)
Empl <- Wage + rnorm(100, 0)

现在我们运行你的回归并绘制线条:

model.ew <- lm(Empl~Wage)
summary(model.ew)
plot(Empl~Wage) # Note. You had the axes flipped here

你的第一个问题是你翻转了轴。因变量(Empl)在垂直轴上。这是你没有得到任何线条的主要原因。要获得预测线,根本不需要循环,只需要使用matlines()进行单个绘图调用:

xval <- seq(min(Wage), max(Wage), length.out=101)
conf <- predict(model.ew, data.frame(Wage=xval), 
    interval="confidence", level=.90)
matlines(xval, conf, col=c("red", "blue", "blue"))

这就是它的全部。 enter image description here