Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a linear regression line on a scatterplot with R?

I tried abline function to create a linear regression line on a scatterplot.

x= c (1.0325477, 0.6746901, 1.0845737, 1.1123872, 1.1060822, 0.8595918, 0.8512941, 1.0148842, 1.0722369, 0.9019220 , 0.8809147, 1.0358256, 0.9903858, 1.0715174 , 1.1034405, 1.0143966,0.9802365, 0.7177169 , 0.9190783, 0.8408701 ) 
y= c (0.8550177, 0.8352162 ,1.0236998, 1.1071665, 0.6768144, 0.8449983 ,0.7616483, 0.8259199, 1.1539598, 1.4125006, 1.0511816, 0.9366184, 1.4101268, 1.2937913, 1.4147219 ,1.2943105 ,0.7859749, 0.6689330, 0.6940164, 0.8093392)
plot(x,y) 
abline(lm(y ~ x))
Error in int_abline(a = a, b = b, h = h, v = v, untf = untf, ...) : 
 plot.new has not been called yet

Any suggestions please

like image 826
lara Avatar asked Mar 11 '12 06:03

lara


People also ask

Can a regression line be plotted in a scatter diagram?

If there is a regression line on a scatter diagram, you can identify outliers. An outlier for a scatter diagram is the point or points that are farthest from the regression line.

How do you add a regression line to a graph?

To add a regression line, choose "Add Chart Element" from the "Chart Design" menu. In the dialog box, select "Trendline" and then "Linear Trendline". To add the R2 value, select "More Trendline Options" from the "Trendline menu. Lastly, select "Display R-squared value on chart".

How do you visualize a linear regression in R?

The basic method of performing a linear regression in R is to the use the lm() function. To see the parameter estimates alone, you can just call the lm() function.


2 Answers

Works fine for me too as for the rest. Try to close and re-open R.

If still problematic, can try:

# put x and y in a data frame
dat<-data.frame(x=x,y=y)
attach(dat)
plot(x,y) 
abline(lm(y ~ x))
like image 141
user1234357 Avatar answered Sep 29 '22 19:09

user1234357


plot(x~y)

abline(lm(x~y))

should fix that code. On MacOs it makes it work.

like image 38
Pamir Erdem Avatar answered Sep 29 '22 18:09

Pamir Erdem