1

I'm having a problem with Loess fit in R. I'm using the default iris dataset included with every R installation. However, when I try to make a loess line, it goes all over the place. The loess line for loess(y~x) is in red, and since I wanted to experiment and see if I was ordering x and y wrong, the line for loess(x~y) is in blue. As you can see, these lines are very clearly wrong. Why is this happening? I can't seem to fix it. Here is the code:

#ignore
library(lattice)
#cloud()

#CODE OF CONCERN BELOW
data <- iris
n<-150
x <- data$Petal.Length
y<-data$Petal.Width
plot(y ~ x)
loess_fit <- loess(y~x)
lines(x, predict(loess_fit), col = "blue")

Here is the picture of what I'm getting:

enter image description here

d.b
  • 32,245
  • 6
  • 36
  • 77
Luke P.
  • 21
  • 3
  • You need to order the points first. x <- sort(data$Petal.Length); y<-data$Petal.Width[order(data$Petal.Length)] – G5W Jun 14 '17 at 16:06
  • ... or order the variables in the lines function call . `lines(x[order(x)], predict(loess_fit)[order(x)], col = "blue")` – user20650 Jun 14 '17 at 16:08
  • 2
    Possible duplicate of [Fit a line with LOESS in R](https://stackoverflow.com/questions/15337777/fit-a-line-with-loess-in-r) Also relevant https://stackoverflow.com/questions/10007830/loess-line-not-plotting-correctly – user20650 Jun 14 '17 at 16:13

1 Answers1

2

You need to order the points before using loess.

x <- sort(data$Petal.Length)
y<-data$Petal.Width[order(data$Petal.Length)] 
plot(y ~ x)
loess_fit <- loess(y~x)
lines(x, predict(loess_fit), col = "blue")

loess curve

G5W
  • 36,531
  • 10
  • 47
  • 80