Vinterwoo
Vinterwoo

Reputation: 3941

Smoothing over a Polynomial curve

Given data that looks like this:

x<-c(0.287,0.361,0.348,0.430,0.294)
y<-c(105,230,249,758,379)

I'm trying to fit several different methods to this data. For this question I'm looking at 2nd order polynomial fits vs Loess fits. To get a smoother curve, I'd like to expand the x data to give me more points to predict over. So for my Loess curve I do this:

Loess_Fit<-loess(y ~ x)
MakeSmooth<-seq(min(x), max(x), (max(x)-min(x))/1000)

plot(x,y)
#WithoutSmoothing
lines(x=sort(x), y=predict(Loess_Fit)[order(x)], col="red", type="l")
#With Smoothing
lines(x=sort(MakeSmooth), y=predict(Loess_Fit,MakeSmooth)[order(MakeSmooth)], col="blue", type="l")

When I attempt to do the same thing with a 2nd order polynomial fit- I get an error

Poly2<-lm(y ~ poly(x,2,raw=TRUE))
plot(x,y)
#WithoutSmoothing
lines(x=sort(x), y=predict(Poly2)[order(x)], col="red", type="l")
#With Smoothing
lines(x=sort(MakeSmooth), y=predict(Poly2,MakeSmooth)[order(MakeSmooth)], col="blue", type="l")

Obviously there is some difference between Poly2 and Loess_Fit, but I don't know what the difference is. Is there a way to smooth out the Poly2 fit as I did with the Loess_Fit?

Upvotes: 0

Views: 862

Answers (1)

Marcelo
Marcelo

Reputation: 4282

For lm, the new data needs to be a data frame:

lines(x=sort(MakeSmooth), y=predict(Poly2,data.frame(x=MakeSmooth))[order(MakeSmooth)], col="blue", type="l")

Upvotes: 1

Related Questions