Rilcon42 - 4 months ago 30

R Question

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

Answer

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