简体   繁体   中英

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.

在此处输入图片说明

Helper questions

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

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

在此处输入图片说明

The mandatory ggplot2 method:

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

在此处输入图片说明

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.

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM