简体   繁体   中英

Plotting a regression line from a known regression equation

I have the following code that calculates a non-parametric regression equation (not lm) from all pairs of data. In this code 'mdns' is the median slope value and 'mdni' is the median intercept so I would then like to plot the points (all x,y pairs) from the data in a scatter plot and then plot the regression line (1) using lm from the raw data and (2) using the calculated non-parametric regression values in the standard equation y=mdni+mdns(X). I know how to do everything except this make a line in a plot from a known equation.

#Calculate pairs of all Slope values
slope<-vector()
 for (i in 1:n){
 for(j in 2:n){ 
   temps<-(data1$y_book[j]-data1$y_book[i])/(data1$x_book[j]-data1$x_book[i])
 if (j>i){  
 slope<-append(slope,temps)}
 }
 }

slope<-slope[!is.na(slope)]
print(slope)
mdns<-median(slope)

#Calculate the Intercept values
inter<-vector()
for (k in 1:n){
    tempi<-(data1$y_book[k] - (mdns*data1$x_book[k]))
    
 inter<-append(inter,tempi)
}
#echo results
print(inter)
mdni<-median(inter)

Not sure what you're looking for, but there are 2 basic ways of plotting a line.

using abline()

plot(NULL,ylim=c(-10,10),xlim=c(-10,10)
abline(a=.4,b= 1) # a= slope, b= intercept (see docs for other options)
# Note line extends completely across plot.

using lines()

plot(NULL,ylim=c(-10,10),xlim=c(-10,10))
x <- seq(from=-9,to=9,length.out=30) 
y <- seq(from=-3,to=3,length.out=30)
lines(cbind(x,y))
# Note line covers only defined extent

See plot, lines, abline documentation. Also see ggplot.

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