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:
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")