3

I'm trying to do a plot "Theoretical Quantiles"X "Standardized Residuals" using ggplot2 package.

I have a lm() model that I used to this plot

library(ggplot2)

model<-lm(mpg~cyl+disp+hp+drat+wt, data=mtcars)

p2<-ggplot(model, aes(qqnorm(.stdresid)[[1]], .stdresid))+geom_point(na.rm = TRUE)
p2<-p2+geom_abline(aes(qqline(.stdresid)))+xlab("Theoretical Quantiles")+ylab("Standardized Residuals")
p2<-p2+ggtitle("Normal Q-Q")+theme_bw()
p2

This code that I founded here https://rpubs.com/therimalaya/43190 make the plot, but returns an error

Error: Aesthetics must be either length 1 or the same as the data (3110): x

and I can't change the xlab or ylab names. How I can solve it?

Hack-R
  • 22,422
  • 14
  • 75
  • 131
Roland
  • 334
  • 2
  • 21
  • Could you please make this reproducible? – Hack-R Oct 01 '16 at 14:57
  • @Hack-R How I do it? – Roland Oct 01 '16 at 14:58
  • Provide the necessary code and data within the question to reproduce the problem. I know you provided a link but they want it within the question and even using the link it's a little unclear as you have to hunt for where you're taking the code from within another function, find the corresponding model and rename the object, etc. http://stackoverflow.com/help/mcve I went ahead and fixed it for you this time. – Hack-R Oct 01 '16 at 14:59
  • 1
    This is _really_ close to a duplicate of http://stackoverflow.com/questions/4357031/qqnorm-and-qqline-in-ggplot2 – hrbrmstr Oct 01 '16 at 15:15

1 Answers1

2
model<-lm(mpg~cyl+disp+hp+drat+wt, data=mtcars)

library(ggplot2)

p2 <- ggplot(model, aes(qqnorm(.stdresid)[[1]], .stdresid))+geom_point(na.rm = TRUE)
p2 <- p2+geom_abline()+xlab("Theoretical Quantiles")+ylab("Standardized Residuals")
p2 <- p2+ggtitle("Normal Q-Q")+theme_bw()
p2

enter image description here

Hack-R
  • 22,422
  • 14
  • 75
  • 131
  • Awesome, you know what is the problem in abline function? – Roland Oct 01 '16 at 15:15
  • @Roland Happy to help. The `aes` argument was not the appropriate length and was apparently totally unncessary. It was a mistake in the example, probably because they were copying from the earlier line which contained an `aes` call and only partially deleted the argument. I'd recommend to email the author so that they can fix their example, though it is 2 years old at this point. – Hack-R Oct 01 '16 at 15:16