Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I plot the residuals of lm() with ggplot?

Tags:

r

ggplot2

lm

I would like to have a nice plot about residuals I got from an lm() model. Currently I use plot(model$residuals), but I want to have something nicer. If I try to plot it with ggplot, I get the error message:

ggplot2 doesn't know how to deal with data of class numeric

like image 766
Lanza Avatar asked Apr 19 '16 23:04

Lanza


3 Answers

Fortify is no longer recommended and might be deprecated according to Hadley.

You can use the broom package to do something similar (better):

library(broom)
y <-rnorm(10)
x <-1:10
mod <- lm(y ~ x)
df <- augment(mod)
ggplot(df, aes(x = .fitted, y = .resid)) + geom_point()
like image 116
Gopala Avatar answered Nov 03 '22 13:11

Gopala


Use ggfortify::autoplot() for the gg version of the regression diagnostic plots. See this vignette.


Example

fit <- lm(mpg ~ hp, data = mtcars)

library(ggfortify)
autoplot(fit)

enter image description here

like image 34
ikashnitsky Avatar answered Nov 03 '22 13:11

ikashnitsky


ggplot wants a data.frame. fortify will make one for you.

y <-rnorm(10)
x <-1:10
mod <- lm(y ~ x)
modf <- fortify(mod)
ggplot(modf, aes(x = .fitted, y = .resid)) + geom_point()
like image 4
Richard Telford Avatar answered Nov 03 '22 13:11

Richard Telford