Lanza
Lanza

Reputation: 597

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

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

Upvotes: 16

Views: 41873

Answers (4)

Koray
Koray

Reputation: 481

Now you can use the ggResidpanel package developed for creating ggplot type residual plots on CRAN. You can find the intro tutorial here!

Upvotes: 4

ikashnitsky
ikashnitsky

Reputation: 3111

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

Upvotes: 17

Gopala
Gopala

Reputation: 10473

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()

Upvotes: 31

Richard Telford
Richard Telford

Reputation: 9923

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()

Upvotes: 4

Related Questions