Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot polynomial regression curve in R

Tags:

plot

r

lm

I have a simple polynomial regression which I do as follows

attach(mtcars)
fit <- lm(mpg ~ hp + I(hp^2))

Now, I plot as follows

> plot(mpg~hp)
> points(hp, fitted(fit), col='red', pch=20)

This gives me the following

Plot of mpg versus hp

Fitted Values

I want to connect these points into a smooth curve, using lines gives me the following

> lines(hp, fitted(fit), col='red', type='b')

Line plot

What am I missing here. I want the output to be a smooth curve which connects the points

like image 449
psteelk Avatar asked Apr 28 '14 06:04

psteelk


2 Answers

I like to use ggplot2 for this because it's usually very intuitive to add layers of data.

library(ggplot2)
fit <- lm(mpg ~ hp + I(hp^2), data = mtcars)
prd <- data.frame(hp = seq(from = range(mtcars$hp)[1], to = range(mtcars$hp)[2], length.out = 100))
err <- predict(fit, newdata = prd, se.fit = TRUE)

prd$lci <- err$fit - 1.96 * err$se.fit
prd$fit <- err$fit
prd$uci <- err$fit + 1.96 * err$se.fit

ggplot(prd, aes(x = hp, y = fit)) +
  theme_bw() +
  geom_line() +
  geom_smooth(aes(ymin = lci, ymax = uci), stat = "identity") +
  geom_point(data = mtcars, aes(x = hp, y = mpg))

enter image description here

like image 135
Roman Luštrik Avatar answered Oct 17 '22 22:10

Roman Luštrik


Try:

lines(sort(hp), fitted(fit)[order(hp)], col='red', type='b') 

Because your statistical units in the dataset are not ordered, thus, when you use lines it's a mess.

like image 32
Davide Passaretti Avatar answered Oct 17 '22 21:10

Davide Passaretti