Reputation: 9765
What is the correct way to plot a curvilinear line of best fit on a graph? I am trying to provide a regression model as a parameter to the line- not specific points. In the model below the correct line should be a perfect fit (because there is no noise in the data). How do I plot the line of best fit from a linear model?
library(lattice)
vals<-data.frame(x=1:10,y=(1:10)^2)
xyplot(x~y,data=vals)
line(lm(x~y,data=vals)) #doesnt work
abline(vals$x,vals$y) #doesnt work
Upvotes: 2
Views: 2148
Reputation: 263301
I'm thinking you may be reversing the order of the arguments in the formula, since the conventional plot of y versus x would be returned from xyplot( y ~ x )
. But if you really do want a linear regression with a second-degree polynomial fit, then use the poly
function in the formula and the predict
function to get the fitted values:
xyplot(x~y,data=vals)
plot(vals$y, predict( lm(x~poly(y, 2), data=vals)) )
It's not an exact fit since you are plotting the square root of x against x.
resid( lm(x~poly(y, 2),data=vals))
#------------------------------
1 2 3 4 5 6 7
-0.57799840 -0.01438720 0.28444720 0.35772841 0.26036947 0.06297286 -0.14816950
8 9 10
-0.27107622 -0.18807651 0.23418989
Another way (which does give an exact fit) is to use the I
function inside the formula:
plot(vals$y, fitted( lm(x~I(y^(1/2) ), data=vals)) )
points(vals, pch="x", col='red')
points(vals$y, vals$x, pch="x", col='red')
Upvotes: 0
Reputation: 7308
To get a regression using the lattice
library, you need to include a type parameter in the xyplot
function. To get a linear regression use "r"
and to get a non-linear regression (which is what you want here) use "smooth"
. So this is what your code should look like
library(lattice)
vals<-data.frame(x=1:10,y=(1:10)^2)
xyplot(x~y,data=vals,type=c("p","smooth"))
The "p"
is for the points and the "smooth"
is for the smooth regression. This will result in a graph that looks like this
Alternative, if you, for some reason, did want a linear regression on this your code would look like this
library(lattice)
vals<-data.frame(x=1:10,y=(1:10)^2)
xyplot(x~y,data=vals,type=c("p","r"))
and your graph would look like this
Upvotes: 1