hhh
hhh

Reputation: 52840

Plot Non-linear Plot for Linear Regression in R

y<-c(0.0100,2.3984,11.0256,4.0272,0.2408,0.0200);
x<-c(1,3,5,7,9,11);
d<-data.frame(x,y)
myLm<-lm(x~y**2,data=d)
plot(d)
lines(x,lm(y ~ I(log(x)) + x,data=d)$fitted.values)
lines(x,lm(y ~ I(x**2) + x,data=d)$fitted.values) % not quite right, smooth plz

It should be smooth plot, something wrong.

enter image description here

Helper questions

  1. What algorithm is used in linear regression?
  2. Explain least squares plotting with Ones -matrix

Upvotes: 1

Views: 14218

Answers (4)

Ben Bolker
Ben Bolker

Reputation: 226182

You need predict in order to interpolate the predictions between the fitted points.

d <- data.frame(x=seq(1,11,by=2),
                y=c(0.0100,2.3984,11.0256,4.0272,0.2408,0.0200))
lm1 <-lm(y ~ log(x)+x, data=d)
lm2 <-lm(y ~ I(x^2)+x, data=d)
xvec <- seq(0,12,length=101)
plot(d)
lines(xvec,predict(lm1,data.frame(x=xvec)))
lines(xvec,predict(lm2,data.frame(x=xvec)))

enter image description here

Upvotes: 9

James
James

Reputation: 66834

The mandatory ggplot2 method:

library(ggplot2)
qplot(x,y)+stat_smooth(method="lm", formula="y~poly(x,2)", se=FALSE)

enter image description here

Upvotes: 6

aatrujillob
aatrujillob

Reputation: 4826

something like:

 plot(d)    
 abline(lm(x~y**2,data=d), col="black")

will make it (if linear, as was implied by the way the question was asked first)

For what you are looking for I think:

  lines(smooth.spline(x, y))

May work as hinted by Dirk.

Upvotes: 3

Dirk is no longer here
Dirk is no longer here

Reputation: 368241

You should spend some time with the 'Appendix A: A sample session' of the 'An Introduction R' manual that came with your program. But here is a start

R> y<-c(0.0100,2.3984,11.0256,4.0272,0.2408,0.0200);
R> x<-c(1,3,5,7,9,11);
R> d<-data.frame(x,y)
R> myLm<-lm(x~y**2,data=d)
R> myLm

Call:
lm(formula = x ~ y^2, data = d)

Coefficients:
(Intercept)            y  
      6.434       -0.147  

and we can plot this as (where I now corrected for your unusual inversion of the roles of x and y):

R> plot(d)
R> lines(d$y,fitted(myLm))

enter image description here

Upvotes: 2

Related Questions