Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plot regression line in R

I want to plot a simple regression line in R. I've entered the data, but the regression line doesn't seem to be right. Can someone help?

x <- c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120)
y <- c(10, 18, 25, 29, 30, 28, 25, 22, 18, 15, 11, 8)
df <- data.frame(x,y)
plot(y,x)
abline(lm(y ~ x))

enter image description here

enter image description here

like image 371
J.doe Avatar asked Sep 28 '16 01:09

J.doe


People also ask

How do you plot a regression line in R?

A regression line will be added on the plot using the function abline(), which takes the output of lm() as an argument. You can also add a smoothing line using the function loess().

How do you plot a regression line in ggplot2?

Adding a regression line on a ggplot You can use geom_smooth() with method = "lm" . This will automatically add a regression line for y ~ x to the plot.

How do I add a line to my plot in R?

The R function abline() can be used to add vertical, horizontal or regression lines to a graph. A simplified format of the abline() function is : abline(a=NULL, b=NULL, h=NULL, v=NULL, ...)


1 Answers

Oh, @GBR24 has nice formatted data. Then I'm going to elaborate a little bit based on my comment.

fit <- lm(y ~ poly(x, 3))   ## polynomial of degree 3
plot(x, y)  ## scatter plot (colour: black)

x0 <- seq(min(x), max(x), length = 20)  ## prediction grid
y0 <- predict.lm(fit, newdata = list(x = x0))  ## predicted values
lines(x0, y0, col = 2)  ## add regression curve (colour: red)

enter image description here

like image 141
Zheyuan Li Avatar answered Sep 24 '22 12:09

Zheyuan Li