Zander
Zander

Reputation: 1018

What exactly happened when predict() is used in lines()?

When I am doing linear modeling, I can just use predict() within lines() and get nice plotting. For example

Year <- 1:15
Sales <- c(301,320,372,423,500,608,721,826,978,1135,1315,1530,1800,2152,2491)
YearSales <- data.frame(Year,Sales)
logYearSales.fit <- lm(log(Sales)~Year)
plot(Year,log(Sales))
lines(Year,predict(logYearSales.fit),col="red",lwd=2)

However, when I combine nls() and lines(), some odds will happen, like this:

library(MASS)
survey1<-survey[!is.na(survey$Pulse)&!is.na(survey$Height),c("Pulse","Height")]
expn <- function(b0,b1,x){
            model.func <- b0 + b1*log(x)
            Z <- cbind(1,log(x))
            dimnames(Z) <- list(NULL, c("b0","b1"))
            attr(model.func,"gradient") <- Z
 model.func
}
survey1<-as.data.frame(survey1)
aa=nls(Height~expn(b0,b1,Pulse), data=survey1,start=c(b0=180,b1=2),trace=TRUE)
plot(survey1)
lines(survey1[,1],predict(aa),col="red",lwd=2)

You can see that the red curve is so thick and as if contaning many lines. But I just cannot understand this.

Upvotes: 0

Views: 77

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270010

The problem is that the Pulse values are not in order. Try

survey1 <- survey1[order(survey1$Pulse), ]

and repeat.

Upvotes: 2

Related Questions